Flutter & Dart: Convert a String into a List and vice versa

Last updated on March 7, 2022 Pennywise Loading... Post a comment

In Flutter and Dart, you can turn a given string into a list (with string elements) by using the split() method.

Example:

// main.dart
void main() {
  const String s =
      "blue red orange amber green yellow purple pink brown indigo";

  final List<String> colors = s.split(' ');
  print(colors);
}

Output:

[blue, red, orange, amber, green, yellow, purple, pink, brown, indigo]

To convert a list of strings to a string, you can use the join() method.

Example:

// main.dart
void main() {
  final List<String> list = [
    'dog',
    'cat',
    'dragon',
    'pig',
    'monkey',
    'cricket'
  ];

  final String result = list.join(', ');
  print(result);
}

Output:

dog, cat, dragon, pig, monkey, cricket

Further reading:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like