Default Value and Type Conversion In Dart| Learning Dart #2| Dart Tutorial #2
Why conversion is Necessary
Dart Type Cast: In any Programing Language we have to Assign or create different Datatypes which we are going to use in the program. Different data types are Declared by different methods, for eg:- for int we use int datatype_name; . This is how we do it. But some time we want to change this data type to another data type which make the program more usable and more functional. For eg:- Converting the string to int for age. etc etc.
So today we will see that how to Convert these data types to another data types in dart language. String to Float, int and many more.
What are Default value
Default values are those value which are assigned to the IDE before we initialize any datatype. These default values are Null and does not return any output, Or In other Words if we does not provide value to variable, it will store Null value. For Eg if we initialize a integer i and then try to print it, it will return null and if we assign a value then it will print a value. Lets see it.
void main(){ int i; print(i); }
Output:-
Null
Type Conversion
Type conversion as we discussed above is the change of a data type to another data type for different use in application. There are 5 different data types in Dart programing language and each one of them can be converted to one another for further use. Lets Understand how this works and what code we have to write in order to do it.
1. String To Integer
For the Conversion of String to Integer we use parse keyword. It is declare as int.parse("value");.
Lets see it
void main(){ int=10; int b=int.parse("20"); print(a+b); }
Output
30
2. String to Double
Now we will convert it String to Double. It will also be done by using parse keyword. The syntax is double name=double.parse("value"). For eg we want to convert a 2.2 which is written in string. so lets see it how it is done.
void main(){ int=10; double b=double.parse("2.2"); print(a+b); }
Output
12.2
3. Integer to String
For Conversion of Integer to String we also use to String keyword. The syntax is: string b=int_value.toString();. Its different from parse keyword. Lets understand how to do it while programing.
void main(){ int=10; string b=50.toString(""); print(b); }
Output
50
void main(){ int=10; string b=50.toString(); print(b.runtimeType); }
Output
String
4. Double to String
For this conversion, it is same like previous conversion. We use toString function in order to do the task. Lets see it.
void main(){ String b=50.238.toString(); print(b); print(b.runtimeType); }
Output
50.238
String