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

如何在Flutter中将指定字符串转换为可索引访问的二维列表?

解决Dart中字符串二维数组转可访问二维列表的问题

首先注意你的原始字符串[[Service, 300, 1], [Service, 4200, 1]]不符合JSON规范——其中的Service没有用双引号包裹,直接用jsonDecode会解析失败。需要先修正字符串格式,再进行解析。

步骤1:修正字符串格式

先把字符串里的Service替换成带双引号的形式:

String serviceWantList = "[[Service, 300, 1], [Service, 4200, 1]]";
// 替换未加引号的Service为带双引号的"Service"
String validJson = serviceWantList.replaceAll('Service', '"Service"');

步骤2:解析为二维列表

修正后就可以用jsonDecode解析,然后转换为二维列表:

List<List<dynamic>> twoDList = (jsonDecode(validJson) as List<dynamic>)
    .map((item) => item as List<dynamic>)
    .toList();

验证访问方式

现在你可以通过索引正常访问:

print(twoDList[0][0]); // 输出 Service
print(twoDList[0][1]); // 输出 300
print(twoDList[1][2]); // 输出 1

适配ListView使用

如果需要在ListView中展示,可以直接遍历这个二维列表:

ListView.builder(
  itemCount: twoDList.length,
  itemBuilder: (context, index) {
    var row = twoDList[index];
    return ListTile(
      title: Text(row[0]),
      subtitle: Text('价格: ${row[1]}, 数量: ${row[2]}'),
    );
  },
);

内容的提问来源于stack exchange,提问作者suraj tiwari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:49:54