【问题标题】:The argument type 'List<dynamic>' can't be assigned to the parameter type 'Iterable<Product>'参数类型“List<dynamic>”不能分配给参数类型“Iterable<Product>”
【发布时间】:2021-11-13 22:03:55
【问题描述】:

这是我的控制器类,因为我正在使用具有 null 安全性的 GetX 控制器

    // ignore_for_file: file_names
    import 'package:get/state_manager.dart';
    import 'package:today/models/product.dart';

    import 'package:today/services/api.dart';

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

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

      void fetchProducts() async {
        try {
          isLoading(true);
          var products = await RemoteServices.fetchProducts();
          if (products != null) {
            productList.value = products;
          }
        } finally {
          isLoading(false);
        }
      }
    }

这是我使用 quicktype.io 创建的模型类

    // To parse this JSON data, do
    //
    //     final product = productFromJson(jsonString);

    import 'dart:convert';

    List<Product> productFromJson(String str) =>
        List<Product>.from(json.decode(str).map((x) => Product.fromJson(x)));

    String productToJson(List<Product> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

    class Product {
      Product({
        required this.id,
        required this.name,
        required this.details,
        required this.price,
        required this.color,
        required this.stock,
        required this.image,
      });

      int id;
      String name;
      String details;
      double price;
      String color;
      int stock;
      String image;

      factory Product.fromJson(Map<String, dynamic> json) => Product(
            id: json["id"],
            name: json["name"],
            details: json["details"],
            price: json["price"].toDouble(),
            color: json["color"],
            stock: json["stock"],
         image: json["image"],
      );

      Map<String, dynamic> toJson() => {
            "id": id,
            "name": name,
            "details": details,
            "price": price,
            "color": color,
            "stock": stock,
            "image": image,
          };
    }

我不知道如何解决这个问题,请帮助我! 编辑:这是我的远程服务类

    // ignore: avoid_web_libraries_in_flutter

// ignore_for_file: avoid_print

    import 'package:http/http.dart' as http;
import 'package:today/models/product.dart';

    class RemoteServices {
      static var client = http.Client();

      static Future<List?> fetchProducts() async {
        try {
          String link = 
    "https://devswagger.aquaticxpressshipping.com/api/Products";
          var url = Uri.parse(link);
          var response = await http.get(
            url,
            headers: {
              "Content-Type": "application/json",
              "Authorization":
                  "Bearer 
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjMyZTJmYTZmLTdlNTEtNGQ4ZC1iNTQ3LTA3YzE5ZGRmYWZiOCIsInJvbGUiOiJVc2VyIiwibmJmIjoxNjMyMTA5NzQ0LCJleHAiOjE2MzI3MTQ1NDQsImlhdCI6MTYzMjEwOTc0NH0.cTROYSpeQHY5wavW-SPbyuHODTzT3wN7oDapy73pkMk",
            },
          );

          if (response.statusCode == 200) {
            var jsonString = response.body;
            return productFromJson(jsonString);
          } else {
            //show error message
            return null;
          }
        } on Error catch (e) {
          print('General Error: $e');
        }
      }
    }

【问题讨论】:

  • RemoteServices.fetchProducts();的代码在哪里?
  • @esentis,我要编辑我的问题
  • fetchProducts()的返回类型改为Future&lt;List&lt;Product&gt;&gt;
  • 您可以添加错误的确切位置吗?调试控制台应该为您提供错误的确切行

标签: flutter dart listview flutter-getx


【解决方案1】:

在名为productFromJson的函数中 分配给

 List<Product> productFromJson(String str) =>
        List<Product>.from(json.decode(str).map<Product>((x) => Product.fromJson(x)).toList());

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 2019-10-05
    • 2020-05-28
    • 2021-11-23
    • 2021-10-24
    • 2021-09-15
    • 2021-10-18
    • 2021-06-26
    • 2021-07-25
    相关资源
    最近更新 更多