{

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

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.

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart