You need to enable JavaScript to run this app. Flutter中如何遍历List<Map>列表循环输出ISBN及其对应值
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何遍历List<Map>列表循环输出ISBN及其对应值

Flutter 循环遍历ISBN列表输出类型与对应值实现

原始输入数据

已有的JSON结构片段如下:

"BooksISBN": [
    {
        "type": "ISBN_13",
        "identifier": "9783846035672"
    },
    {
        "type": "ISBN_10",
        "identifier": "384603567X"
    }
],

目标输出效果

逐行打印/渲染的预期结果为:

ISBN_13 : 9783846035672
ISBN_10 : 384603567X

可直接复用的实现方案

  • 最基础的for-in循环写法,逻辑直观适合快速调试
    // 假设已完成JSON解析,得到对应的图书ISBN列表
    final List<Map<String, String>> booksISBN = [
      {"type": "ISBN_13", "identifier": "9783846035672"},
      {"type": "ISBN_10", "identifier": "384603567X"}
    ];
    
    // 逐行输出
    for (final isbnItem in booksISBN) {
      print('${isbnItem["type"]} : ${isbnItem["identifier"]}');
    }
    
  • 函数式批量拼接写法,适合直接生成完整输出字符串
    final fullOutput = booksISBN.map((isbnItem) {
      return '${isbnItem["type"]} : ${isbnItem["identifier"]}';
    }).join('\n');
    print(fullOutput);
    
  • 项目级规范写法(强类型Model),避免动态类型引发的运行时异常
    1. 先定义ISBN信息实体类
      class ISBNInfo {
        final String type;
        final String identifier;
      
        ISBNInfo({required this.type, required this.identifier});
      
        factory ISBNInfo.fromJson(Map<String, dynamic> json) {
          return ISBNInfo(
            type: json['type'] as String,
            identifier: json['identifier'] as String,
          );
        }
      }
      
    2. 完成列表解析与遍历输出
      // 从原始JSON中解析出强类型ISBN列表
      final List<ISBNInfo> isbnList = (rawJson['BooksISBN'] as List)
          .map((itemJson) => ISBNInfo.fromJson(itemJson))
          .toList();
      
      // 逐行输出匹配格式的内容
      for (final isbn in isbnList) {
        print('${isbn.type} : ${isbn.identifier}');
      }
      

注意:不要在循环遍历的过程中直接修改正在遍历的列表元素,否则会触发Dart的并发修改异常。


内容的提问来源于stack exchange,提问作者PHP Pharaoh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 17:36:01