Dart| Flutter: Convert List into String examples

This tutorial shows multiple ways to create an immutable list.

Sometimes, You need to Convert List<String> into a Single String.

How to Convert List String to String in Dart?

There are multiple ways we can do

  • use join() method

List has a join method that returns the string with an optional separator. default optional parameter is empty.

It iterates each element and calls the element.toString() append the result with a separator.

List.join(optionalSeparator)

Here is a program.

void main() {
  List<String> words = ["one", "two", "three"];
  print(words);
  print(words.join());
  print(words.join(" "));
  print(words.join("-"));
}

Output:

[one, two, three]
onetwothree
one two three
one-two-three
  • use reduce() method

The list has reduce() function, which reduces the list of elements into a single element.

iterates the element in a list and applies a function, function append the string, return the string.

String reduce(String Function(String, String) combine)

Here is an example

void main() {
  List<String> words = ["one", "two", "three"];
  print(words);
  String result = words.reduce((value, element) => value + '-' + element);
  print(result);
}

Output:

[one, two, three]
one-two-three
  • using for index loop

This is another to iterate the list of elements using for index loop append to an already declared variable, Finally print the variable to a console

Here is an example

void main() {
  List<String> words = ["one", "two", "three"];
  print(words);
  var result = "";
  for (int i = 0; i < words.length; i++) {
    result = result + words[i].toString();
  }
  print(result);
}

Output:

[one, two, three]
onetwothree

Conclusion

Learned multiple ways to join and convert a list to a single string in dart or flutter with examples.

  • join
  • reduce method
  • for index loop

For string joining, join is simple and easy to implement.