虽然这个问题已经被问过几次,但我没有从我看到的人那里得到帮助。就这样,
我的资产文件夹中有一个模拟 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":
[
{.....},
{.....}
]
}
答案 0 :(得分:1)
Result是map而不是list,因为result是数据,data是list,所以先从map中提取数据,然后遍历list。
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)
答案 1 :(得分:1)
改变这个:
for (var u in result)
为此:
for (var u in result["data"])