Dart/Flutter – How to format String (String Interpolation)

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

We can even put a complex expression inside the brackets. In below example, we define an anonymous function to return the length of the
provided string, then we call that function and pass “password” as a parameter.

I don’t recommend this since it’s hard to read your code.

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.

Check another blog here if you want to learn more about How to print an object in Dart.

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}


This post is also available on Medium and Linkedin.

Happy coding!

And please don’t hesitate to add your comments! 🤟

Tagged : / /
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x