In this tutorial we would learn about some basic but important coding techniques. Flutter is based on Dart language and like any other language it has its own code writing structure. In today’s tutorial we would learn about What are Literals and String Interpolation in Flutter Dart Explained with Example Tutorial.
Contents in this project Literals and String Interpolation in Flutter Dart Explained With Example Tutorial:
1. Literals in Dart Flutter Explained :-
Literals are the only information which is yet not stored in any variable and written standalone in somewhere in code. The information can be in any format like Boolean type value, Integer value, String value or Double value. Literals are the free values which is ready to assign to any data type variable in dart. Literals are basically same in all programming languages. See the below example to understand literals properly.
1 2 3 4 5 6 7 8 9 10 11 |
void main() { 'Flutter-Examples'; 1234567890; 1.44; true; } |
2. How to Assign Literals to Variables in Dart Flutter :-
Now we know what are literals, Next thing is to know how to assign them to property their type of variables. Because literals freely cannot be used. See the below example to understand how to assign Literals to variables.
1 2 3 4 5 6 7 8 9 10 11 |
void main() { var website = 'Flutter-Examples'; int id = 1234567890; double pi = 1.44; bool isNote = true; } |
3. String Interpolation in Flutter Dart :-
Basically we would use + Plus symbol to connect two or multiple string in most of programming languages but in Dart using + Plus symbol is sees as a bad programmer habit. So here comes the String interpolation in dart which stops us to use + symbol to connect two string and open many ways to used string. See the below example to understand properly.
Without String Interpolation:
1 2 3 4 5 6 7 |
String name = 'Flutter-Examples.com'; // Without String Interpolation. String message = 'Welcome to our Website ' + name ; //Printing message on terminal. print(message); |
Output:
With String Interpolation:
In below example we are using $ Dollar sign to extract value from string variable and using variable directly in current string without using Plus symbol.
1 2 3 4 5 6 7 8 9 |
void main() { String name = 'Flutter-Examples.com'; String message = 'Welcome to our Website $name'; print(message); } |
Output:
4. Use String Interpolation on other data type variables:-
After learning about string interpolation on String we would learn about applying string interpolation on various data type variables. See the below example. Now in below example we are multiplying width and length to calculate area of rectangle so whatever written in curly brackets are treated as expression using string interpolation.
1 2 3 4 5 6 7 8 |
void main() { double length = 50; double width = 40; print('Area of Rectangle is ${ length * width }'); } |
Output: