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
相关产品推荐
相关产品推荐

