【发布时间】:2021-01-20 13:58:13
【问题描述】:
我正在尝试使用颤振从我的 json 文件 categories.json 获取值,但总是出错或不显示,我真的不知道出了什么问题
这是我的 main.dart
Future<List<Category>> loadData() async {
String jString = await rootBundle.loadString("assets/categories.json");
List<dynamic> jRes = jsonDecode(jString);
List<Category> datas = jRes.map((e) => Category.fromJson(e)).toList();
return datas;
}
Container(
child: FutureBuilder<List<Category>>(
future: loadData(),
builder: (context, data) {
if (data.connectionState != ConnectionState.waiting &&
data.hasData) {
var userList = data.data;
return ListView.builder(
itemCount: userList.length,
itemBuilder: (context, index) {
var userData = userList[index];
return Column(
children: [
Text("Category: ${userData.catName}"),
],
);
});
} else {
return Center(
child: CircularProgressIndicator(),
);
}
})),
还有我的 model.dart
class Category {
String catId;
String catName;
SubCategory subcat;
Category({this.catId, this.catName, this.subcat});
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
catId: json['cat_id'],
catName: json['category'],
subcat: SubCategory.fromJson(json['cat_subcategory']),
);
}
Map<String, dynamic> toJson() {
return {
"cat_id": catId,
"category": catName,
};
}
}
class SubCategory {
String subName, subImage;
SubCategory({this.subName, this.subImage});
factory SubCategory.fromJson(Map<String, dynamic> json) {
return SubCategory(subName: json['sub_name'], subImage: json['sub_image']);
}
Map<String, dynamic> toJson() {
return {
"sub_name": subName,
"sub_image": subImage,
};
}
}
最后是我的 categories.json 文件
[{
"category": "Design & Creativity",
"cat_id": "1",
"cat_subcategory": [
{
"sub_name": "Ads",
"sub_image": "https://images.unsplash.com/photo-1589838017489-9198a27bd040?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8YWR2ZXJ0aXNlbWVudHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
}
]
}]
//There are more of them
我运行它时面临的问题是它只在我的 main.dart 中显示CircularProgressIndicator(),当我删除 if 语句 时,它说Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null.请问我该如何解决这个问题,如果您需要更多解释,请告诉我
PS:当我检查loadData() 值时,它显示type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
编辑:谢谢大家的回答,但我所做的是使用这个网站生成一个模型model generator
我能够获得价值
【问题讨论】:
-
如果您删除
if语句,您的数据将无法初始化。您是否尝试检查数据的有效状态?loadData方法返回有效结果? -
@fartem 我如何检查它是否有效。对不起,我是新来的颤振
-
您可以调试您的应用程序或在日志中打印您的变量。
-
@fartem 它说
type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' -
尝试将您的文件解析为对象,而不是列表。使用
Map<String, dynamic>而不是List<dynamic>。您可以发布您的 JSON 文件吗?