如何将String转换为List <String>

Two*_*San 5 dart flutter

我有这个String.

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

我想把它转换成List<String>.问题是它也返回方括号.我想列表看起来["one", "two", "three", "four"]不是这样[["one", "two", "three", "four"]].我怎样才能正确转换?

Gün*_*uer 11

您的字符串看起来像有效的JSON,所以这应该适合您:

import 'dart:convert';
...

var String a = '["one", "two", "three", "four"]';
var ab = json.decode(a);
print(ab[0]); // return ["one"
Run Code Online (Sandbox Code Playgroud)

  • 如果列表不是有效的 JSON,该怎么办 (2认同)
  • 然后您需要使用自定义代码解析字符串。 (2认同)

Ahm*_*fat 6

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
}
Run Code Online (Sandbox Code Playgroud)