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

Flutter开发中如何从字符串中解析提取id、season等多个字段内容

解决方案

你的colors数组内的元素本身就是Map类型,无需从toString()生成的字符串中截取内容,直接通过键名即可精准获取对应字段值:

  • 取id字段:使用colors[index]['id']
  • 取season字段:使用colors[index]['season']

如果需要点击列表项时打印两个字段,给ListTile添加onTap回调即可。修改后的完整代码如下:

import 'package:flutter/material.dart';

final colors = [
  {'id': 'red', 'season': 'winter',},
  {'id': 'green', 'season': 'spring',}
];

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ListView.builder(
            itemBuilder: (context, index) => ListTile(
              // 点击列表项时打印两个字段
              onTap: () {
                print('id: ${colors[index]['id']}, season: ${colors[index]['season']}');
              },
              title: Card(
                // 直接拼接两个字段显示
                child: Text('id: ${colors[index]['id']},season: ${colors[index]['season']}')
              )
            ),
            itemCount: colors.length
          )
        )
      )
    );
  }
}

该方式不需要处理字符串长度差异问题,不管字段值的字符长度怎么变化,都能准确获取对应内容,适配所有场景。


内容的提问来源于stack exchange,提问作者born.a.bot

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:18:03