flutter 如何在Dart 3中使用记录解析JSON数据?

4dc9hkyq  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(193)

如何在Dart 3中使用记录、模式匹配和JSON解构来解析JSON数据?
以下是Dart 2中的情况。

型号

class Category {
  final int id;
  final String title;

  Category({
    required this.id,
    required this.title,
  });

  factory Category.fromJson(Map<String, dynamic> data) {
    return Category(
      id: data['id'] as int,
      title: data['title'] as String,
    );
  }
}

API Repository Class方法中

class ApiRepository {

Future<List<Category>> fetchCategory() async {
      final res = await get(...);

      List<dynamic> decodedData = jsonDecode(res.body);

      final fetchedCategories =
          decodedData.map((e) => Category.fromJson(e)).toList();

        return fetchedCategories;
    }
}
wd2eg0qa

wd2eg0qa1#

因为这对我来说是新的,这是我所假设的。我很高兴反馈:
让我们简单地看看模式匹配是做什么的。
假设我们的类为:

class Category {
  final int id;
  final String title;

  Category({
    required this.id,
    required this.title,
  });

}

让我们有一个对象。普通老json

var jsonObject = 
{
'title': 'Hello World',
'id': 10,
};

我们可以使用模式匹配来分配这个对象的值。我更喜欢交换箱。考虑到所有的安全措施,这是理想的。

Category? category;
switch (jsonObject) {
case {'id': int id, 'title': String title}:
category =  Category(id: id, title: title);
default:
}

现在如果你打印ID,你会得到10。

print(category?.id);

使用jsonObjects列表,我们可以简单地做到:

var jsonObjectList = [
{
'title': 'Hello World',
'id': 10,
},
    {
'title': 'Hello World 2',
'id': 11,
}, 
  ];

List<Category?> categories = jsonObjectList.map((json){
switch (json) {
case {'id': int id, 'title': String title}:
return Category(id: id, title: title);
default:
return null;
}
}).toList();

对于复杂的情况,避免OOP似乎是一件很痛苦的事情。注:这是我的理解。请纠正或评论您的意见,以及这样我就可以改善

相关问题