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

  print(sb.toString()); // Hello John


Learned multiple ways to append a string with another string using plus operator, String interpolation and StringBuffer write method.

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
You'll get a notification every time a post gets published here.

Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example