25

I have this String.

  var String a = '["one", "two", "three", "four"]';
  var ab = (a.split(','));
  print(ab[0]); // return ["one"

I want to convert this to List<String>. The problem is it returns square bracket too. I want to List looks this ["one", "two", "three", "four"] not [["one", "two", "three", "four"]]. How can I convert this properly?

Daibaku
  • 11,416
  • 22
  • 71
  • 108

2 Answers2

44

Your string looks like a valid JSON, so this should work for you:

New (proper generic type

import 'dart:convert';
...

var a = '["one", "two", "three", "four"]';
var ab = json.decode(a).cast<String>().toList();
print(ab[0]); // returns "one"

Old

import 'dart:convert';
...

var a = '["one", "two", "three", "four"]';
var ab = json.decode(a);
print(ab[0]); // returns "one"
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
5
void main(){
     String listA = '["one", "two", "three", "four"]';
     var a = jsonDecode(listA);
     print(a[0]); // print one

     String listB = 'one,two,three,four';
     var b = (listB.split(','));
     print(b[0]); // print one
}
Dave
  • 3,073
  • 7
  • 20
  • 33
Ahmed Raafat
  • 162
  • 4
  • 6