Flutter GetX -在UI中集成API

hmae6n7t  于 2023-03-04  发布在  Flutter
关注(0)|答案(1)|浏览(122)

我是一个flutter初学者。使用 dart 语言。我试图在flutter中使用GetX集成API和UI。但是当从JSON文件中检索产品时,我得到了以下错误。
1.'静态未来取积()异步{
提取产品时出错-"主体可能正常完成,导致返回" null ",但返回类型" FutureOR "可能是不可为空的类型。"
1.变量响应=等待客户端. get('https://.........../');
Uri中出现错误-"无法将参数类型" String "分配给参数类型" Uri "。"
产品型号:

ProductModel productFromJson(String str) => ProductModel.fromJson(json.decode(str));

String productToJson(ProductModel data) => json.encode(data.toJson());

class ProductModel{

ProductModel({
    required this.id,
    required this.title,
    required this.description,
    required this.price,
    required this.discountPercentage,
    required this.rating,
    required this.stock,
    required this.brand,
    required this.category,
    required this.thumbnail,
    required this.images,
});
int id;
String title;
String description;
int price;
double discountPercentage;
double rating;
int stock;
String brand;
String category;
String thumbnail;
List<String> images;

factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
    id: json["id"],
    title: json["title"],
    description: json["description"],
    price: json["price"],
    discountPercentage: json["discountPercentage"]?.toDouble(),
    rating: json["rating"]?.toDouble(),
    stock: json["stock"],
    brand: json["brand"],
    category: json["category"],
    thumbnail: json["thumbnail"],
    images: List<String>.from(json["images"].map((x) => x)),
);

Map<String, dynamic> toJson() => {
    "id": id,
    "title": title,
    "description": description,
    "price": price,
    "discountPercentage": discountPercentage,
    "rating": rating,
    "stock": stock,
    "brand": brand,
    "category": category,
    "thumbnail": thumbnail,
    "images": List<dynamic>.from(images.map((x) => x)),
};

}
API代码:

import 'package:http/http.dart' as http;
import 'package:practice/productmodule/models/product_model.dart';

class ApiService {
static var client = http.Client();
static Future<ProductModel> fetchProducts() async {
var response = await client.get('https://.......1');
if (response.statusCode == 200) {
  var jsonString = response.body;
  return productFromJson(jsonString);
}

}}
有人能帮我吗?先谢了!

eoigrqb6

eoigrqb61#

你必须改变

var response = await client.get('https://.......1');

这与

var response = await client.get(Uri.parse('https://.......1'));

因为Http客户端需要URI而不是字符串。

相关问题