2 Ways to Create Multi-Line Strings in Dart

Last updated on May 17, 2021 Pennywise Loading... Post a comment

This short aritcle shows you two ways to create multi-line strings in Dart (and Flutter as well).

Using Triple Quotes

Both triple-single-quote (”’) and triple-double-quote (“””) work fine.

Example:

void main() {
  String s1 = '''
  This is a 
  multi-line
  string 
  ''';
  
  print(s1);
  
  String s2 = """
  Lorem ipsum dolor sit amet,
  consectetur 'adipiscing elit'. 
  Vivamus id sapien nec felis pulvinar feugiat.
  """;
  print(s2);
}

Output:

  This is a 
  multi-line
  string 
  
  Lorem ipsum dolor sit amet,
  consectetur 'adipiscing elit'. 
  Vivamus id sapien nec felis pulvinar feugiat.

Note that anything between the starting and ending quotes becomes part of the string so this example has a leading blank. The strings will also contain both blanks and newlines.

Using Adjacent String Literals

This approach doesn’t add any extra blanks or newlines. If you want some line break, you need to add “\n”.

Example:

void main() {
   String s1 = 'He thrusts his fists'
     'against the posts'
     'and still insists'
     'he sees the ghosts.';
   print(s1);
   print('-------'); // Just a horizontal line
  
   String s2 = 'He thrusts his fists\n'
     'against the posts\n'
     'and still insists\n'
     'he sees the ghosts.';
   print(s2);
}

Output:

He thrusts his fistsagainst the postsand still insistshe sees the ghosts.
-------
He thrusts his fists
against the posts
and still insists
he sees the ghosts.

Conclusion

You’ve learned how to make multi-line strings in Dart through some examples. Continue exploring more interesting stuff about Dart, an awesome programming language for app development, take a look at the following articles: Sorting Lists in Dart and Flutter (5 Examples)Flutter & Dart: Get File Name and Extension from Path/URLUnderstanding Typedefs (Type Aliases) in Dart and FlutterFlutter & Dart: Regular Expression Examples.

You can also take a tour around our Flutter topic page, or Dart topic page for the latest tutorials and examples.

Related Articles

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