Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter how to convert String to List<String>

Tags:

flutter

dart

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?

like image 823
Daibaku Avatar asked Sep 12 '18 06:09

Daibaku


People also ask

Can you convert a string to a list?

Strings can be converted to lists using list() .

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

How do you split a string in Flutter?

split method Null safety allMatches, and returns the list of the substrings between the matches, before the first match, and after the last match. const string = 'Hello world! '; final splitted = string. split(' '); print(splitted); // [Hello, world!];


2 Answers

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

import 'dart:convert';
...

var a = '["one", "two", "three", "four"]';
var ab = json.decode(a);
print(ab[0]); // returns "one"
like image 90
Günter Zöchbauer Avatar answered Sep 28 '22 08:09

Günter Zöchbauer


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
}
like image 21
Ahmed Raafat Avatar answered Sep 28 '22 08:09

Ahmed Raafat