What is String Interpolation in Dart? | String and String Interpolation in Dart| Learning Dart #3| Dart Tutorial #2
What is String Interpolation?
String Interpolation is the Way of replacing placeholders with the actual value which is in the string or we have provided to the string. String Interpolation is done in many different languages like Python, C++, C and many more. Now as we are learning DART there is the different way of doing so. Every language has their own way of doing so, lets See this and understand it how it works.
Why it is Necessary?
In any programing language we define create strings and objects. We use these Strings and Objects in differernt different places, for different purposes. If we try to make and create every other place the code becomes difficult to read and takes too much time. If we create a String and initialize its value to anywhere we are using it, it will make our task easier and will save too much time of the Programmer. If we want to make changes in the code or add something new, it is easier to do so if we use interpolation technique.
How to Do it
In Dart language we have to use dollar ($) sign for interpolation. It can be used as $ sign followed by the string name. When we will exectute the program we will have the value of the string which we want to print there. Lets understand it by an example:-
void main() { String carname = 'BMW'; print('My car is $carname'); }
Output
My Car is BMW
Another Example
void main() { int number1 = 10; int number2 = 7; print('The sum of $number1 and $number2 is ${number1 + number2}.'); }
Output
The sum of 10 and 7 is 17.
Concatenation Operator
We can store values of String in '' Single Quote or "" Double Quote. It will print the same output, there will be no difference. Lets see it how it can be done.
void main() { print('Jai Shree Ram.'); }
void main() { print("Jai Shree Ram."); }
Output
Jai Shree Ram.
What is Concatenation Operator in Dart?
Concatenation Operator is an Operator which is used to Add Multiple string into a single string and print the output. It is done by using '+' operator. Lets Understand how it is done by Looking at a example of this.
Example
void main(){ String a="Dhirendra Singh Naruka"; print("My Name Is" +a); }
Output
My Name is Dhirendra Singh Naruka
void main(){ print("My Name is" + " Rahul"); }
Output
My Name is Rahul