You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Dart 3的Records、模式匹配和JSON解构解析JSON数据?

Dart 3 vs Dart 2:JSON解析实现对比

Dart 2 传统实现方式

数据模型类

通过定义实体类并实现fromJson工厂方法完成JSON到对象的转换:

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仓库中的解析方法

发起请求、解码JSON后,通过map调用fromJson生成实体列表:

class ApiRepository {
  Future<List<Category>> fetchCategory() async {
    final res = await get(...); // 省略具体HTTP请求逻辑
    List<dynamic> decodedData = jsonDecode(res.body);
    
    final fetchedCategories = decodedData.map((e) => Category.fromJson(e)).toList();
    return fetchedCategories;
  }
}

Dart 3 新特性简化实现

Dart 3新增的Records、模式匹配和JSON解构特性,可大幅简化JSON解析流程,无需编写繁琐的工厂方法。

用Records定义数据结构

通过Record类型定义Category的数据结构,替代传统实体类:

typedef Category = ({int id, String title});

结合模式匹配的解析方法

利用模式匹配直接解构JSON Map,完成类型检查和数据转换:

class ApiRepository {
  Future<List<Category>> fetchCategory() async {
    final res = await get(...); // 省略具体HTTP请求逻辑
    final List<dynamic> decodedData = jsonDecode(res.body);
    
    final fetchedCategories = decodedData.map((json) {
      if (json case {'id': int id, 'title': String title}) {
        return (id: id, title: title);
      }
      throw FormatException('无效的Category JSON格式: $json');
    }).toList();
    
    return fetchedCategories;
  }
}

也可以使用switch表达式进一步简化代码:

final fetchedCategories = decodedData.map((json) => switch(json) {
  {'id': int id, 'title': String title} => (id: id, title: title),
  _ => throw FormatException('无效的Category JSON格式: $json'),
}).toList();

优势说明

  • 无需编写fromJson工厂方法,减少样板代码
  • 模式匹配自带类型检查,降低类型转换异常风险
  • Records轻量灵活,适合仅需存储数据的场景

内容的提问来源于stack exchange,提问作者Anmol Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:32:05