Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What is string interpolation in Dart?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

String interpolation is the process of inserting variable values into placeholders in a string literal.

To concatenate strings in Dart, we can utilize string interpolation. We use the ${} symbol to implement string interpolation in your code.

Code

void main() {
// Assigning values to the variable
String shot1 = "String";
String shot2 = "interpolation";
String shot3 = "in";
String shot4 = "Dart programming";
// Concatenate all values using
// string interpolation without space
print('$shot1$shot2$shot3$shot4');
// Concatenate all values using
// string interpolation with space
print('\n');
print('Now, include space between each value');
print('\n');
print('$shot1 $shot2 $shot3 $shot4');
}

To interpolate the value of Dart expressions within strings, use ${}. The curly braces {} are skipped if the expression is an identifier.

void main() {
String text = 'Educative';
// text is an identifier
// so the {} can be omitted
print('The word $text has ${text.length} letters');
}

Example

The example below uses string interpolation in a list and map operation.

void main(){
List mylist = [10, 20, 30, 40, 50, 60];
// Using map on list items
List newList = [mylist.map((i) => i * i)];
print("The list $mylist was squared to give a new list $newList");
// Creating Map items
Map myMap = {"1": "String", "2": "literals"};
print("This is a shot on ${myMap['1']} Interpolation");
}

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring