1

After reading a line from a file, I have the following String:

"[0, 1, 2, 3, 4]"

What is the best way to convert this String back to List<int>?

Hadysata
  • 172
  • 6
NirG
  • 71
  • 1
  • 7

2 Answers2

9

Just base on following steps:

  1. remove the '[]'
  2. splint to List of String
  3. turn it to a int List

Sth like this:

  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();

Update:

You can also do this with the json.decode() as @pskink suggested if you confirm all content is int type, but you may need to cast to int in order to get the List<int> as default it will returns List<dynamic> type.

eg.

List<int> list = json.decode(value).cast<int>();
CbL
  • 734
  • 5
  • 22
  • With the introduction of null-safety, this code gives an error, as the result of `tryParse` cannot be added to `List`. See https://stackoverflow.com/questions/66896648/how-to-convert-a-listt-to-listt-in-null-safe-dart for an explanation of how to handle this. – Patrick O'Hara Feb 27 '23 at 17:06
0

You can convert String list to int list by another alternate method.

void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
stringList.map((e){
var intValue = int.tryParse(e);
intList.add(intValue!);
print(intList);
});
print(a);
}

Or by using for in loop

void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
for (var i in stringList){
int? value = int.tryParse(i);
intList.add(value!);
print(intList);
 }
}
Raju Gupta
  • 752
  • 5
  • 10