String Interpolation in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

There are times when we want to make use of variables inside the statement that is made up of string values.

We know that we can add two strings together in Dart with the help of the + symbol operator. But to make use of a variable in between the strings that we are concatenating, we need to add one more + symbol and then type the name of the variable, which works okay when it comes to small statements.

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = "Tutorials";
   var collegeName = "DTU";
   print("Name is " + name + " college Name is " + collegeName);
}

Output

Name is Tutorials college Name is DTU

In the above example, we have both the variables of type string, but what about the case, where we want to make use of an integer in between the print() function statement.

Example

Consider the example shown below −

void main(){
   String name = "Tutorials";
   var collegeID = 10602;
   print("Name is " + name + " college Name is " + collegeID);
}

In the above example, we have a string and we are trying to assign an int to it (collegeID). Dart doesn't allow such a process, as it is statically typed, and the compiler will throw an error.

Output

Error: A value of type 'int' can't be assigned to a variable of
type 'String'.
   print("Name is " + name + " college Name is " + collegeID);

The workaround for the above problem is to make use of string interpolation, where we pass the variable into the string statement with a special syntax.

Syntax

'print this ${variable}'

Example

Consider the example shown below −

 Live Demo

void main(){
   String name = "Tutorials";
   var collegeID = 10602;
   print("Name is ${name} and collegeID is ${collegeID}");
}

Output

Name is Tutorials and collegeID is 10602
raja
Published on 24-May-2021 11:56:00
Advertisements