You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter GetX API对接UI遇空安全及实例化错误求助

问题解决方案

1. 修正控制器的产品列表类型

你当前定义的productList = ProductModel().obs是单个产品的可观测对象,但实际需要的是产品列表,且ProductModel的构造函数要求必填参数,直接调用ProductModel()必然报错。修改为可观测的列表类型:

class ProductController extends GetxController {
  var isLoading = true.obs;
  // 改为可观测的空产品列表
  var productList = <ProductModel>[].obs;
}

2. 处理ProductModel的空安全兼容问题

JSON返回的字段可能存在null值,而你的模型字段均为非空类型,需在fromJson方法中为可能为null的字段设置默认值,或根据业务需求将字段改为可空类型。

方案一:给字段设置默认值(推荐,保证非空)

修改fromJson工厂方法,为每个可能为null的字段添加兜底默认值:

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

方案二:将字段改为可空类型(适合允许字段为空的场景)

如果业务允许部分字段为null,可将模型字段改为可空类型,同时调整构造函数和toJson方法:

class ProductModel {
  ProductModel({
    required this.id,
    required this.title,
    required this.description,
    required this.price,
    this.discountPercentage,
    this.rating,
    required this.stock,
    this.brand,
    this.category,
    required this.thumbnail,
    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: json["images"] != null ? List<String>.from(json["images"].map((x) => x)) : null,
      );

  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": images != null ? List<dynamic>.from(images!.map((x) => x)) : null,
      };
}

3. 补充API请求逻辑(控制器示例)

在控制器中添加获取产品数据的方法,完成API与UI的对接:

class ProductController extends GetxController {
  var isLoading = true.obs;
  var productList = <ProductModel>[].obs;

  @override
  void onInit() {
    fetchProducts();
    super.onInit();
  }

  void fetchProducts() async {
    try {
      isLoading(true);
      // 调用你的API服务获取产品列表
      var products = await ApiService.fetchProducts();
      if (products != null) {
        productList.assignAll(products);
      }
    } finally {
      isLoading(false);
    }
  }
}

内容的提问来源于stack exchange,提问作者Priya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:43:19