多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ## 映射 映射的方式解析动态的结构更加方便 json ``` const documentJson = ''' { "metadata": { "title": "My Document", "modified": "2023-05-10" }, "blocks": [ { "type": "h1", "text": "Chapter 1" }, { "type": "p", "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, { "type": "checkbox", "checked": false, "text": "Learn Dart 3" } ] } '''; ``` bad ``` // 解析json (String, {DateTime modified}) getMetadata() { if (_json.containsKey('metadata')) { var metadataJson = _json['metadata']; if (metadataJson is Map) { var title = metadataJson['title'] as String; var localModified = DateTime.parse(metadataJson['modified'] as String); return (title, modified: localModified); } } throw const FormatException('Unexpected JSON'); } ``` good ``` (String, {DateTime modified}) getMetadata() { if (_json case { 'metadata': { 'title': String title, 'modified': String localModified, } }) { return (title, modified: DateTime.parse(localModified)); } else { throw const FormatException('Unexpected JSON'); } } ```