Strings in Dart

Strings represent textual data. Let's see how they work!

Overview of Strings

  • Strings are represented as a collection of characters.
  • We can use single quotes to define strings in Dart.
ℹ️ Note

We can also use double quotes to represent strings, but single quotes are more common in Dart.

String Interpolation

  • In most of the programming languages, we use + to concatenate/join two strings. But in Dart, we can use $variable_name or ${expression} inside an enclosed single quotes to use the power of String Interpolation.
void main() {
  String language = 'Dart';
  String framework = 'Flutter';

  print('We are learning the $language programming language. The $framework is built on $language.'); // string interpolation
}
Expected Output

We are learning the Dart programming language. The Flutter is built on Dart.

ℹ️ Note

So, we can use $ for using the value of the variables and ${} when we need to evaluate an expression.

Multiline Strings

  • We can use triple quotes (‘’’) to create multiline strigs when we want a string to span across multiple lines.
ℹ️ Note

Triple quotes can be 3 single quotes (‘’’) or 3 double quotes(“”“).

Make sure that you also use the closing quotes!

  • In the following highlighted code, \n is used to insert a newline character. This is called an Escape Sequence.
void main() {
  String multiString = '''\n Plot No - 123
 Main Street, Odisha, India
 Pin - 751012''';

  print('Here is my address: $multiString');
}
Expected Output

Here is my address: Plot No - 123 Main Street, Odisha, India Pin - 751012

ℹ️ Note

Just like regular strings, multiline strings also support string interpolation.

String Methods

  • These are some of the most used string methods:
String method Usage
.length employeeName.length
.toUpperCase() employeeName.toUpperCase()
.toLowerCase() employeeName.toLowerCase()
.contains() employeeName.contains('e')
.substring() employeeName.substring(3)
.replaceAll() employeeName.replaceAll('e', 'a')
.trim() ' Hi '.trim()
  • More information on strings can be found at: Strings

Getting Input from Users

  • We can ask the user to type something when we want that functionality in our program.
  • We can get input from the user using readLineSync().
import 'dart:io';

void main() {
  print('Enter your name:');
  String? userName = stdin.readLineSync();
  print('Hello, $userName!');
}
  • In the highlighted code above, the ? is used to specify that the userName variable can be null. That means when the user doesn’t enter any value, we must handle that case; otherwise it would result in an error!
ℹ️ Note

When we use the readLineSync method, the program actually stops and wait for the user to provide the input.

This blocking behavior enables the program to not continue onto the next line until the user presses Enter.

⭐ Important

Make sure to import the dart:io package by pressing Ctrl+. while the cursor is at the readLineSync method.