当前位置: 首页 > 知识库问答 >
问题:

Flutter"未处理的异常:类型'_InternalLinkedHashMap'不是类型'Iterable'的子类型"

轩辕华辉
2023-03-14

虽然这个问题已经被问了几次,但我没有从我看到的那些人那里得到帮助。所以就这样,

我有一个模拟json文件在我的资产文件夹:recipe.json

这是配方。充当我的模型类的dart

class RecipeModel {
  final String id;
  final String name;
  final String videoLink;
  final String author;
  final String category;
  final String time;
  RecipeModel({
    required this.id,
    required this.name,
    required this.videoLink,
    required this.author,
    required this.category,
    required this.time,
  });

  factory RecipeModel.fromJson(Map<String, dynamic> json) {
    return RecipeModel(
      id: json['id'],
      name: json['name'],
      videoLink: json['videoLink'],
      author: json['author'],
      category: json['category'],
      time: json['time'],
    );
  }
}

这里是HomeScreen.dart

  Future<List<RecipeModel>> getRecipeData() async {
    // var response = await http.get(
    //   Uri.https("jsonplaceholder.typicode.com", 'users'),
    // );
    String response = await DefaultAssetBundle.of(context)
        .loadString('assets/json/recipe.json');
    var result = json.decode(response);
    List<RecipeModel> recipes = [];
    for (var u in result) {
      RecipeModel recipe = RecipeModel(
        id: u['id'] ?? "",
        name: u['name'] ?? "",
        videoLink: u['videoLink'] ?? "",
        author: u['author'] ?? "",
        category: u['category'] ?? "",
        time: u['time'] ?? "",
      );
      recipes.add(recipe);
    }

    print(recipes.length);

    return recipes;
  }

  @override
  void initState() {
    super.initState();
    getRecipeData();
  }

如您所见,我希望在页面加载后立即获取数据,并将所述数据保存在列表中,然后可以在gridview中使用。但每次加载屏幕时,我都会出现以下错误:

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>

我接着看了一些教程,完全忽略了与我不想要的模型相关的任何东西。我错过了什么?我需要做什么才能在一个列表中得到结果,然后在网格视图中使用?

我的json数据有点像这样:

{
  "data":
  [
    {.....},
    {.....}
  ]
}

共有2个答案

单于高逸
2023-03-14

改变这个:

for (var u in result)

为此:

for (var u in result["data"])
督德泽
2023-03-14

结果是图而不是列表,因为结果是数据,数据是列表,所以首先从图中提取数据,然后迭代列表。

Future<List<RecipeModel>> getRecipeData() async {
  // var response = await http.get(
  //   Uri.https("jsonplaceholder.typicode.com", 'users'),
  // );
  String response = await DefaultAssetBundle.of(context)
      .loadString('assets/json/recipe.json');
  var result = json.decode(response);

  var resultList = result["data"];

  List<RecipeModel> recipes = [];
  for (var u in resultList) {
    RecipeModel recipe = RecipeModel(
      id: u['id'] ?? "",
      name: u['name'] ?? "",
      videoLink: u['videoLink'] ?? "",
      author: u['author'] ?? "",
      category: u['category'] ?? "",
      time: u['time'] ?? "",
    );
    recipes.add(recipe);
  }

  print(recipes.length);

  return recipes;
}

如果您对接收的数据类型有任何疑问,只需检查runtimeType。

print(result.runtimeType)

 类似资料: