Dart string interpolation:
In dart, strings can be created by either using a single quote or double quotes. Using string interpolation, we can insert the result of an expression or a variable in a string. ${expression} is used to insert an expression. For variables, we can skip the {}.
Example of string interpolation:
Below is an example of string interpolation:
import 'dart:io';
void main() {
print('Enter your age: ');
var age = int.parse(stdin.readLineSync());
print('You have entered: $age');
print(
'${age < 10 ? "Sorry, You are not allowed to play this game !!" : "You can start playing this game"}');
}
Here,
- We are taking the age of the user as input and storing it in the variable age.
- The print statements are using string interpolation.
- The first print statement is printing the age that was entered. Note that we are not using {} to print the age.
- The second print statement is using an expression to print a message. This expression gives a different message based on the age value. If age is smaller than 10, it gives a message and if it is larger than 10, it gives another message. You can also use a separate function to return the message and call this function from here.
- Note that, in the second print statement, we are using {} and double quotes. {} is required since this is an expression. But, instead of double quotes, we can also use single quotes since dart supports both.
Sample output:
It will give output as like below:
Enter your age:
12
You have entered: 12
You can start playing this game
Enter your age:
25
You have entered: 25
You can start playing this game
Enter your age:
9
You have entered: 9
Sorry, You are not allowed to play this game !!