How to concatenate two strings in a dart?| Flutter By Example
Learn how to concatenate two strings in Dart and flutter programming with examples.
In Java languages, you can use the +
symbol or the append method used to append strings.
Since String is an immutable object. There are multiple ways we can append strings.
String concatenate or append in dart
For example, if given strings(str1=Hello, Str2=John) are appended, then the output is hello John`.
-using + operator
The +
symbol appends the first string with the second string and the result is appended string.
It is simple and easy.
void main() {
var str = "Hello";
var str1 = " John";
print(str + str1); // Hello John
}
- string interpolation:
In this, the String variable is appended with $ and enclosed in single quotes. if a string variable is str, you can use either one of '$str'
and '${str}'
void main() {
var str = "Hello";
var str1 = " John";
print('$str $str1'); // Hello John
print('${str}${str1}'); // Hello John
}
Since the string is immutable, string interpolation is recommended over the +
symbol.
- StringBuffer class
The StringBuffer
class can be used for complex string object creation over String object.
It has a method write()
for append a string, writeAll()
for Iterable String Finally, Returns theStringbuffer toString()
method.
Here is an example code
void main() {
var str = "Hello";
var str1 = " John";
final sb = StringBuffer();
sb.write(str);
sb.write(str1);
print(sb.toString()); // Hello John
}
Conclusion
Learned multiple ways to append a string with another string using plus operator, String interpolation and StringBuffer write method.