【问题标题】:The argument type 'List<Categories>' can't be assigned to the parameter type 'Iterable<Categories>'参数类型“List<Categories>”不能分配给参数类型“Iterable<Categories>”
【发布时间】:2021-07-25 17:55:20
【问题描述】:

这是我的模型类类别

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

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

class Categories {
  Categories({
    this.id,
    this.name,
    this.parentId,
    this.slug,
    this.position,
    this.status,
  });

  int id;
  String name;
  int parentId;
  String slug;
  int position;
  int status;

  factory Categories.fromJson(Map<String, dynamic> json) => Categories(
    id: json["id"],
    name: json["name"],
    parentId: json["parent_id"],
    slug: json["slug"],
    position: json["position"],
    status: json["status"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "parent_id": parentId,
    "slug": slug,
    "position": position,
    "status": status,
  };
}

我的 apiServices

static Future<List<Categories>> fetchCategories() async {
String url = "/categories/all";
var response = await http.get(BASE_URL + url);
if(response.statusCode == 200) {
return categoriesFromJson(response.body).toList();
} else {
return null;
}
}

我的控制器中的api调用函数

var categoryNames = <Categories>[].obs;
void fetchCategories() async {
    try{
      isLoading(true);

      var res = await ApiServices.fetchCategories();
      if(res !=null){
        categoryNames.addAll(res);
      }
    }finally{
      isLoading(false);
    }
  }

在控制器中,而 categoryNames.addAll(res) 中的 res 用红色弯曲线加下划线,并显示上述错误消息。当我对 apiService 的 categoryNews 和 fetchCategories() 使用相同的类型时,为什么会出现此错误。任何帮助将不胜感激。

【问题讨论】:

  • 我尝试更改 var categoryNames = [];列出 categoryNames = [];但仍然有同样的错误。
  • categoriesFromJson 中的.map() 之后添加一个.toList(),因为map 返回一个Iterable。
  • 我在从 api 调用返回值时转换为 List。另外,我尝试在模型类的 categoriesFromJson 方法中的 .map() 之后添加 .toList() ,但是红色的弯曲线不会走。
  • 我刚刚尝试过,但没有帮助......我也在 app.quicktype.io 的帮助下生成了模型类
  • 你试过了吗? Categories.fromJson(json.decode(str))。我又看了一下代码,不需要List.from.map()

标签: api flutter flutter-layout flutter-dependencies flutter-test


【解决方案1】:

尝试像这样明确定义类型

List<Categories> categoryNames = [];

还要确保从您的.map() 返回一个列表并将.toList() 添加到末尾

【讨论】:

  • 检查.map()
  • 让它像List&lt;Categories&gt;.from(json.decode(str).map((x) =&gt; Categories.fromJson(x)).toList())
  • 另外,我想通知我在app.quicktype.io的帮助下生成了模型类
  • 打印res ?它是什么类型的?
  • 类型为 List
猜你喜欢
  • 2020-05-28
  • 2021-06-26
  • 2021-11-13
  • 2021-12-24
  • 2021-07-10
  • 2019-10-05
  • 2021-11-23
  • 2021-07-04
  • 2021-12-10
相关资源
最近更新 更多