This tutorial shows you how to join a List
to a String
with any separator in Dart/Flutter.
Using String join()
Dart's List
class has an instance method join()
that can be used to join a List
of any type to a String
.
String join([String separator = ""])
Below is a simple example in which we are going to join a list of strings into a string. Without passing the separator parameter, the default separator (empty string) will be used. Therefore, the result is the same as concatenating the values without a separator.
List<String> values = ['dart', 'flutter', 'programming'];
print(values.join());
Output:
dartflutterprogramming
If you pass an argument, it will be used as the separator between elements.
List<String> values = ['dart', 'flutter', 'programming'];
print(values.join(','));
Output:
dart,flutter,programming
In case you want to transform the value first, you can create a chain and map
the values first before adding join
at the end of the chain.
List<String> values = [' dart', 'flutter ', 'programming'];
String result = values
.map((val) => val.trim())
.join(',');
print(result);
Output:
dart,flutter,programming
Join Object
How to handle If the list is a collection of objects, not simple data types (such as string, double, or int? Dart uses toString
method of the object's class. Therefore, if you create your own class and you want to join a list of the object into a string, it is necessary to override toString
method.
class Item {
int id;
String name;
Item({this.id, this.name});
@override
String toString() {
return '{id: $id, name: $name}';
}
}
Item item1 = Item(id: 1, name: 'Item One');
Item item2 = Item(id: 2, name: 'Item Two');
Item item3 = Item(id: 3, name: 'Item Three');
List items = [item1, item2, item3];
print(items.join(','));
Output:
{id: 1, name: Item One},{id: 2, name: Item Two},{id: 3, name: Item Three}
Without overriding toString
, the output will be:
Instance of 'Item',Instance of 'Item',Instance of 'Item'
That's all about how to convert a List
into a String
with separator. If you want to perform the reverse thing, you can read our tutorial about how to convert a List
with any delimiter to a String
.