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.

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

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.

print(r'Path: C:\Program Files\Coflutter');
print(r'I have $100 USD');

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)).

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).

9. String interpolation.

Like other modern languages, Dart supports string interpolation which allows us to place values of variables inside a string.

final coflutter = 'Coflutter';
print('Hello ${coflutter}.'); 


For more details, I created a blog 👉 Interesting facts about String Interpolation. Check it out!

Tagged : / /
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x