英文:
How can I read Data from a JSON File and display it in Flutter Widgets?
问题
以下是翻译好的部分:
我想要使用我的JSON文件将其中的所有信息存储以在Flutter中显示。
每当我遇到这个错误时:
_TypeError(类型'_InternalLinkedHashMap <String,dynamic>'不是类型'List <dynamic>'的子类型)
这是我的文件:
db.json
breed_page.dart
有人可以帮助我解决这个错误或者向我展示更好的做法吗?
通常,名称和图像应从JSON文件中读取,然后在列表瓦片中显示为圆形图像或文本。我还检查了我的JSON文件并尝试了其他函数,如这个,但没有帮助。顺便说一下,我是Flutter的新手。
ListView.builder(
itemCount: breeds.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Image.network(breeds[index]['img']),
title: Text(breeds[index]['name']),
onTap: () {
// TODO: 跳转到品种详情页
},
);
},
);
英文:
I would like to use my JSON file to store all the info in it to display in Flutter.
Everytime i get this Error:
_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>')
Here are my Files:
db.json
breed_page.dart
Can someone help me solving this error or show me a better way to do this?
Normally, the name and image should be read from the JSON file and then displayed in the list tile as a circle image or as text. I have also checked my JSON file and tried other functions like this one but nothing helped. By the way I am a newbie in Flutter
ListView.builder(
itemCount: breeds.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: Image.network(breeds[index]['img']),
title: Text(breeds[index]['name']),
onTap: () {
// TODO: Navigate to breed details page
},
);
},
);
答案1
得分: 1
你解码的 JSON 字符串是 Map<String,dynamic>
而不是 List<dynamic>
。
{
"breeds": [
{
List
是从键 breeds
获取的值。
解决方法:
Future<List<dynamic>> fetchBreeds() async {
String jsonString = await rootBundle.loadString('lib/db.json');
final tempDecoded = json.decode(jsonString);
// 现在通过键 "breeds" 获取列表
final breeds = tempDecoded["breeds"];
return breeds;
}
英文:
your decoded json string is Map<String,dynamic>
not a List<dynamic>
{
"breeds":[
{
the List
are a value from key breeds
Workaroud:
Future<List<dynamic>> fetchBreeds() async {
String jsonString = await rootBundle.loadString('lib/db.json');
final tempDecoded = json.decode(jsonString);
// now get the list with key breeds
final breeds = tempDecoded["breeds"];
return breeds;
}
答案2
得分: -1
json.decode(jsonString);
似乎将数据从 String
转换为 Map<String, dynamic>
而不是 List<dynamic>
。
请查阅语言文档,以确保您使用了正确的 JSON 返回类型。
https://api.dart.dev/stable/2.19.3/dart-convert/jsonDecode.html
英文:
json.decode(jsonString);
seems to be converting the data from String
to Map<String, dynamic>
instead of List<dynamic>
Please go through the language docs to check if you're using the right return type for your json
https://api.dart.dev/stable/2.19.3/dart-convert/jsonDecode.html
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论