【发布时间】:2021-07-21 06:35:49
【问题描述】:
虽然这个问题已经被问过几次,但我没有从我看到的人那里得到帮助。就这样吧,
我的资产文件夹中有一个模拟 json 文件:recipe.json
这是充当我的模型类的recipe.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>
我看到一些教程完全忽略了与我不想要的模型相关的任何内容。我在这里想念什么? 我需要做什么才能在列表中获取结果,然后我可以在 gridview 中使用?
我的json数据有点像这样:
{
"data":
[
{.....},
{.....}
]
}
【问题讨论】:
-
结果是
map而不是list,因为结果是data,而data是一个列表,所以首先从map中提取data,然后遍历列表。