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

Dart技术问询:如何将指定格式的String转换为List<int>

在Dart中将数组格式字符串转为List

方法一:利用JSON解析(最简单)

你的字符串格式本身就是标准的JSON数组,直接借助dart:convert里的json.decode解析,再转成List<int>即可:

import 'dart:convert';

void main() {
  String inputStr = "[137, 80, 78, 71, 13, 10, 26, 10]";
  List<int> resultList = List<int>.from(json.decode(inputStr));
  print(resultList); // 输出: [137, 80, 78, 71, 13, 10, 26, 10]
}

这个方法的前提是输入字符串必须是合法的JSON数组格式,否则解析会失败。

方法二:手动处理字符串(灵活可控)

如果不想依赖JSON库,或者需要处理格式稍有偏差的字符串,可以手动处理:

void main() {
  String inputStr = "[137, 80, 78, 71, 13, 10, 26, 10]";
  // 移除首尾的方括号
  String trimmedStr = inputStr.substring(1, inputStr.length - 1);
  // 分割、清理、转int
  List<int> resultList = trimmedStr.split(',')
      .map((item) => item.trim()) // 去掉每个元素前后的空格
      .where((item) => item.isNotEmpty) // 过滤空字符串(避免分割后出现空内容)
      .map((item) => int.parse(item)) // 转成int类型
      .toList();
  
  print(resultList); // 输出: [137, 80, 78, 71, 13, 10, 26, 10]
}

处理异常情况

如果输入字符串可能包含非数字内容,建议用int.tryParse代替int.parse,避免程序崩溃:

List<int> resultList = trimmedStr.split(',')
    .map((item) => item.trim())
    .where((item) => item.isNotEmpty)
    .map((item) => int.tryParse(item))
    .where((num) => num != null) // 过滤转失败的null值
    .cast<int>()
    .toList();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:45:07