Flutter中如何将列表对象的tag字段拼接为单个字符串?
Flutter:将列表对象的tag字段拼接为指定格式字符串
核心解法
先提取列表中所有对象的tag字段,再根据格式需求调整拼接:
步骤1:提取所有tag字段
遍历列表,用map方法取出每个元素的tag值,转为字符串列表:
List phrase = [ {'tag': 'This is a flutter'}, {'tag': 'learning session', 'icon': icon.flutter}, {'tag': 'Therefore,', 'icon': icon.learningHat}, {'tag': 'Login here'}, ]; // 提取所有tag,转为字符串列表 List<String> allTags = phrase.map((item) => item['tag'] as String).toList();
步骤2:按期望格式拼接
根据你要的输出,将前两个tag拼接后加句号,再处理后两个tag的标点和大小写,最后组合:
// 处理第一部分:前两个tag拼接加句号 String firstSection = allTags.sublist(0, 2).join(' ') + '.'; // 处理第二部分:修正标点和大小写 String correctedThirdTag = allTags[2].replaceAll(',', ''); String correctedFourthTag = allTags[3].replaceFirst('L', 'l'); String secondSection = '$correctedThirdTag $correctedFourthTag.'; // 最终结果 String finalOutput = '$firstSection $secondSection'; // 输出:This is a flutter learning session. Therefore login here.
你之前的问题分析
phrase.toString()会把整个列表转为带括号、大括号的字符串,不是你要的纯tag内容;phrase[index]['tags']有两个错误:一是每个对象的键是tag而非tags,二是index只能取单个元素的tag,无法获取所有元素的tag。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

