简体   繁体   English

为什么我不能从 json - flutter 获取数据值

[英]Why can't i get data value from json - flutter

Am trying to get values from my json file categories.json using flutter but am always getting error or its not showing and I don't really know what is wrong This is my main.dart Am trying to get values from my json file categories.json using flutter but am always getting error or its not showing and I don't really know what is wrong This is my 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(),
          );
        }
      })),

and my model.dart和我的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,
    };
  }
}

and lastly my categories.json file最后是我的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

The problem am facing when I run it is that it only shows me the CircularProgressIndicator() in my main.dart and when I remove the if statement , it says Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null.当我运行它时面临的问题是它只在我的main.dart中向我显示CircularProgressIndicator() ,当我删除if 语句时,它说Another exception was thrown: NoSuchMethodError: The getter 'length' was called on null. Please how do I go about solving this problem and if you need more explanation then tell me请问我如何解决这个问题,如果您需要更多解释,请告诉我

PS: When I check the loadData() value it says type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' PS:当我检查loadData()值时,它说type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

EDIT: Thank you all for the answers but what i did was to generate a model using this website model generator编辑:谢谢大家的回答,但我所做的是使用此网站model 生成器生成 model

and i was able to get the value我能够获得价值

Personally, when I want to load data from json file, I do this:就个人而言,当我想从 json 文件加载数据时,我这样做:

  Future<List<Category>> loadData() async {
    List<Category> datas = [];
    return rootBundle.loadString("assets/categories.json").then((value) {
      List<dynamic> jRes = jsonDecode(value);
      jRes.forEach((element) {
        datas.add(Category.fromJson(element));
      });
      return datas;
    });
  }

Also, in SubCategory class此外,在子类别class

factory SubCategory.fromJson(Map<String, dynamic> json) {
    return SubCategory(subName: json['sub_name'], subImage: json['sub_image']);
  }

Your fromJson() require Map<String, dynamic> .您的fromJson()需要Map<String, dynamic>

But if you look at your file但是如果你看你的文件

"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"
            }
           
          
        ]

You can see that cat_subcategory is a List可以看到cat_subcategory是一个 List

So you are giving a List to your SubCategory.fromJson() instead of a Map.所以你给你的 SubCategory.fromJson ()一个列表,而不是一个 Map。 If you want to give a Map, you can simply give the first index of your list如果你想给出一个 Map,你可以简单地给出你列表的第一个索引

Your Category.fromJson() become您的 Category.fromJson() 成为

factory Category.fromJson(Map<String, dynamic> json) {
    return Category(
      catId: json['cat_id'],
      catName: json['category'],
      subcat: SubCategory.fromJson(json['cat_subcategory'][0]),
    );
  }

Change your model.dart class更改您的 model.dart class

class Category {
String category;
String catId;
List<CatSubcategory> catSubcategory;

Category({this.category, this.catId, this.catSubcategory});

Category.fromJson(Map<String, dynamic> json) {
category = json['category'];
catId = json['cat_id'];
if (json['cat_subcategory'] != null) {
  catSubcategory = new List<CatSubcategory>();
  json['cat_subcategory'].forEach((v) {
    catSubcategory.add(new CatSubcategory.fromJson(v));
  });
}}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['category'] = this.category;
data['cat_id'] = this.catId;
if (this.catSubcategory != null) {
  data['cat_subcategory'] =
      this.catSubcategory.map((v) => v.toJson()).toList();
}
return data;
}}

class CatSubcategory {
String subName;
String subImage;

CatSubcategory({this.subName, this.subImage});

CatSubcategory.fromJson(Map<String, dynamic> json) {
subName = json['sub_name'];
subImage = json['sub_image'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sub_name'] = this.subName;
data['sub_image'] = this.subImage;
return data;
}}

And Replace并替换

List<Category> datas = jRes.map((e) => Category.fromJson(e)).toList();

with

List<Category> datas = List<Category>.from(jRes.map((category)=> Category.fromJson(category)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM