4 C
New York
Thursday, February 2, 2023

2 Ways to Create Multi-Line Strings in Dart

This short article shows you two different 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.Advertisements

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

AdvertisementsThis 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 fistsn'
     'against the postsn'
     'and still insistsn'
     '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:

Advertisements

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

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles