How to Join List Array to String in Flutter/Dart

In this example, you will learn how to join List array items to string in Flutter or Dart. Here, we are joining the List of plain strings and List of objects to a single String output. We will use a simple function that concat List items to one String.

List<String> strlist = ["Hello", "How", "Are", "You"];

String str1 = strlist.join();
print(str1); //Output: HelloHowAreYou

Here, the List.join() method concat all the string values inside the List, and output as a single string. You can also add a separator while joining like below:

List<String> strlist = ["Hello", "How", "Are", "You"];

String str2 = strlist.join(" ");
print(str2); //Output: Hello How Are You

Here, we put whitespace as a separator, therefore there is different output than above.

Object Class:

class Student{
  String name, address;
  Student({required this.name, required this.address});

  @override //don't forgot to add this override
  String toString() {
    return "Name: $name, Address: $address";
    //the string format, you can put any format you like
  }
}

Don't forget to add toString() override while making a class. The format you provide here will be used to convert this object to a string. Now, join the list of this object like below:

List<Student> studentlist = [
  Student(name: "John", address: "India"),
  Student(name: "Krishna", address: "Nepal"),
  Student(name: "Gita", address: "Canada")
];

String str3 = studentlist.join(" | ");
print(str3);
//Output:
//Name: John, Address: India | Name: Krishna, Address: Nepal | Name: Gita, Address: Canada

//Without toString() override on class
//Instance of 'Student'Instance of 'Student'Instance of 'Student'

Here, the format of the string is retrieved from the toString() override at the object class.

In this way, you can join List Array to one String in Dart or Flutter.

No any Comments on this Article


Please Wait...