flutter 如何将字符串转换为二维列表

odopli94  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(226)

我想把字符串转换成2d数组在 dart 扑

[[Service, 300, 1], [Service, 4200, 1]]

这是一个字符串,我想把它转换成一个列表,这样我就可以在Flutter中使用下面的ListView。

List<String> stringList = (jsonDecode(serviceWantList) as List<dynamic>).cast<String>();

我试过了,但我没有得到我想要的结果。
我想访问这样的列表

[[Service, 300, 1], [Service, 4200, 1]]

我想在2列表中转换它,所以我访问像index[0][0]index[0][1]等。

aemubtdh

aemubtdh1#

jsonDecode将不起作用,因为字符串不是有效的JSON。尝试执行以下操作:

String input =
      '[[Service is the best, 300, 1], [Man is awesome, 4200, 1],[Service is the best, 300, 1], [Man is awesome, 4200, 1]]';

  input = input.replaceAllMapped(
      RegExp(r'([a-zA-Z ]+)(?=,)'), (match) => '"${match.group(0)}"');
  List<List<dynamic>> output = List.from(jsonDecode(input))
      .map((e) => List.from(e).cast<dynamic>())
      .toList();
  print(output[0][0].runtimeType);
  print(output[0][1].runtimeType);
  print(output[1][0].runtimeType);
  print(output[1][1].runtimeType);

问题是字符串包含未加引号的文本,这在JSON中是不允许的;因此,我们需要将字符串中的所有非数字值括在双引号(“)中。

相关问题