如何将字符串中的数字列表转换为dart中的int列表
从文件中读取一行后,我有以下字符串:
"[0, 1, 2, 3, 4]"
将此字符串转换回的最佳方法是什么List<int>?
回答
只需基于以下步骤:
- 去除那个 '[]'
- 夹板到字符串列表
- 把它变成一个 int List
像这样:
List<int> list =
value.replaceAll('[', '').replaceAll(']', '')
.split(',')
.map<int>((e) {
return int.tryParse(e); //use tryParse if you are not confirm all content is int or require other handling can also apply it here
}).toList();
更新:
json.decode()如果您确认所有内容都是 int 类型,您也可以使用as @pskink 建议执行此操作,但您可能需要强制转换为 int 以获得List<int>默认返回List<dynamic>类型。
例如。
List<int> list = json.decode(value).cast<int>();