13.8 C
New York
Saturday, December 3, 2022

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

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

AdvertisementsOutput:

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.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles