DEV Community

Cover image for String in Dart/Flutter – Things you should know
Phuc Tran
Phuc Tran

Posted on

String in Dart/Flutter – Things you should know

String is an important data type in almost programming languages (if not all). Dart is not an exception. In this post, I will show you several things that you may (or may not) know about String in Dart/Flutter.

1. String literals can be wrapped in single quotes or double quotes.

// Both are accepted in Dart const singleQuoteString = 'Hello Coflutter'; const doubleQuoteString = "Hello Coflutter"; 

👉 It is recommended that you make it consistently, choose one style and use it throughout your code.

2. If you use pedantic as your linter, single quotes is preferred.

// Warning with pedantic const s1 = "Hello Coflutter"; // Warning: Only use double quotes for strings containing single quotes. const s2 = "Hello. I'm Coflutter"; // OK 

👉 You can find the rule here.

3. Use a backslash ( \ ) to escape special characters.

print("I'm Coflutter"); print("I\'m Coflutter"); print("I\'m \"Coflutter\""); print('Path: C:\\Program Files\\Coflutter'); 
// Output I'm Coflutter I'm Coflutter I'm "Coflutter" Path: C:\Program Files\Coflutter 

4. “Raw” string (r before string) can be used to escape special character too.

// "Raw" string print(r'Path: C:\Program Files\Coflutter'); print(r'I have $100 USD'); 
// Output Path: C:\Program Files\Coflutter I have $100 USD 

5. Triple quotes can be used to represent multiple lines string (instead of using “new line” character (\n)).

// Multiple lines string print( '''This is a multiple line string, created by Coflutter ''' ); 

6. Override toString( ) method in your object to have beautiful output when print( ).

👉 Find details and example here.

7. String supports padding methods: paddingLeft( ) and paddingRight( ).

👉 Find details and example here.

8. String multiplication is supported in Dart. But the string must be placed before the multiply operator (Permutation does not work).

const fire = '🔥'; for (var i = 0; i <= 3; i++) { // final output = i * fire; // -> Error: The argument type 'String' can't be assigned to the parameter type 'num'. final output = fire * i; print(output); } 
🔥 🔥🔥 🔥🔥🔥 

9. String interpolation.

👉 Interesting facts about String Interpolation.

Top comments (0)