Interesting facts about String Interpolation in Dart

Phuc Tran
Nextfunc Co., Ltd
Published in
2 min readAug 16, 2020

In this post, we will learn a few interesting things about String interpolation in Dart.

1. Syntax:

The value of an expression can be placed inside a string using:

${expression}

final coflutter = 'Coflutter';
print('Hello ${coflutter}. Your name has ${coflutter.length} characters.');

// Hello Coflutter. Your name has 9 characters.

2. If the expression is a single identifier (variable), the brackets ({ }) can be omitted.

final coflutter = 'Coflutter';
print('Goodbye $coflutter.');

// Goodbye Coflutter.

3. if..else inside the bracket

I don’t recommend this because it will make your code more difficult to read, but here I just show you what the language can do.

final password = 'password';
print('The password is ${password.length > 8 ? 'OK' : 'weak'}!');

// The password is weak!

4. Complex expression inside the brackets

final password = 'password';
print('Password length is: ${((String pwd) {
return pwd.length;
})(password)}.');

// Password length is: 8.

5. Object

If an object is placed inside the brackets, Dart internally calls toString() on that object. So that you don’t need to call toString() yourself.

(I also wrote a blog about How to print an object in Dart here).

class Student {
final String name;
final int age;

Student(this.name, this.age);

@override
String toString() {
return 'Student: {name: ${name}, age: ${age}}';
}
}

final student = Student('Coflutter', 30);
print('Info: $student');

// Info: Student: {name: Coflutter, age: 30}

Happy coding! And please don’t hesitate to add your comments!

The original post is here. You can find other posts about Dart/Fluter on my Coflutter blog.

ABOUT NEXTFUNC

Nextfunc is a software development outsourcing company specialized in delivering services and solutions for web, mobile apps using native SDK and cross-platform frameworks. As we are living in such an ever-evolving world, our team truly understand the frequent changes in the needs and demands of our customers. With a team full of young yet talented specialists, we are here to provide customers across the globe with the best cutting-edge technologies.

--

--