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.
void main() {// Assigning values to the variableString shot1 = "String";String shot2 = "interpolation";String shot3 = "in";String shot4 = "Dart programming";// Concatenate all values using// string interpolation without spaceprint('$shot1$shot2$shot3$shot4');// Concatenate all values using// string interpolation with spaceprint('\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 omittedprint('The word $text has ${text.length} letters');}
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 itemsList newList = [mylist.map((i) => i * i)];print("The list $mylist was squared to give a new list $newList");// Creating Map itemsMap myMap = {"1": "String", "2": "literals"};print("This is a shot on ${myMap['1']} Interpolation");}