ASHWIN RAJEEV
ASHWIN RAJEEV

Reputation: 2891

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.

Upvotes: 66

Views: 101257

Answers (6)

gauhun
gauhun

Reputation: 407

Let's think we have two strings

String a = 'Hello';
String b = 'World';
String output;

Now we want to concat this two strings

output = a + b;
print(output);

Hello World

Upvotes: 2

Mark O'Sullivan
Mark O'Sullivan

Reputation: 10778

The answer by Günter covers the majority of the cases of how you would concatenate two strings in Dart.

If you have an Iterable of Strings it will be easier to use writeAll as this gives you the option to specify an optional separator

final list = <String>['first','second','third'];
final sb = StringBuffer();
sb.writeAll(list, ', ');
print(sb.toString());

This will return

'first, second, third'

Upvotes: 5

Yogendra Singh
Yogendra Singh

Reputation: 2241

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

Upvotes: 10

Baig
Baig

Reputation: 4995

Easiest way

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

Upvotes: 5

M. Syamsul Arifin
M. Syamsul Arifin

Reputation: 163

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

Upvotes: 12

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657376

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.

Upvotes: 106

Related Questions