How to concatenate two string in Dart?

I am new to Dart programming language and anyone help me find the best string concatenation methods available in Dart.

I only found the plus (+) operator to concatenate strings like other programming languages.


Solution 1:

There are 3 ways to concatenate strings

String a = 'a';
String b = 'b';

var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh' 
         'abcdefgh abcdefgh abcdefgh abcdefgh';

Usually string interpolation is preferred over the + operator.

There is also StringBuffer for more complex and performant string building.

Solution 2:

Suppose you have a Person class like.

class Person {
   String name;
   int age;

   Person({String name, int age}) {
    this.name = name;
    this.age = age;
  }
}

And you want to print the description of person.

var person = Person(name: 'Yogendra', age: 29);

Here you can concatenate string like this

 var personInfoString = '${person.name} is ${person.age} years old.';
 print(personInfoString);

Solution 3:

If you need looping for concatenation, I have this :

var list = ['satu','dua','tiga'];
var kontan = StringBuffer();
list.forEach((item){
    kontan.writeln(item);
});
konten = kontan.toString();

Solution 4:

Easiest way

String get fullname {
   var list = [firstName, lastName];
   list.removeWhere((v) => v == null);
   return list.join(" ");
}