{

How to concatenate two strings in a dart?| Flutter By Example


concatenate two string in Dart

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

+ 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 an 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

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 Stringbuffer 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example