Welcome to the comprehensive Data Types in Dart Tutorial! This codelab will teach you everything you need to know about data types in Dart programming language. Data types are fundamental to programming as they help categorize and organize different types of data in your code.
What you'll learn:
var keyword and type inferencePrerequisites:
✅
: This tutorial provides a comprehensive foundation for understanding all data types in Dart, which is essential for writing robust and efficient code!
Data types help you categorize all the different types of data you use in your code. For example, numbers, texts, symbols, etc. The data type specifies what type of value will be stored by the variable. Each variable has its data type.
Data types are categories that define what kind of data a variable can hold. They help the compiler understand how to store and manipulate the data efficiently.
Dart supports the following built-in data types:
✅
: Understanding data types is crucial for writing efficient and bug-free Dart code!
When you need to store numeric values in Dart, you can use either int or double. Both int and double are subtypes of num. You can use num to store both int or double values.
void main() {
// Declaring Variables
int num1 = 100; // without decimal point.
double num2 = 130.2; // with decimal point.
num num3 = 50;
num num4 = 50.4;
// For Sum
num sum = num1 + num2 + num3 + num4;
// Printing Info
print("Num 1 is $num1");
print("Num 2 is $num2");
print("Num 3 is $num3");
print("Num 4 is $num4");
print("Sum is $sum");
}
Output:
Num 1 is 100
Num 2 is 130.2
Num 3 is 50
Num 4 is 50.4
Sum is 330.59999999999997
✅
: The num type is very flexible and can handle both integers and floating-point numbers!
String helps you to store text data. You can store values like "I love dart", "New York 2140" in String. You can use single or double quotes to store string in Dart.
void main() {
// Declaring Values
String schoolName = "Diamond School";
String address = "New York 2140";
// Printing Values
print("School name is $schoolName and address is $address");
}
Output:
School name is Diamond School and address is New York 2140
If you want to create a multi-line String in Dart, you can use triple quotes with either single or double quotation marks:
void main() {
// Multi Line Using Single Quotes
String multiLineText = '''
This is Multi Line Text
with 3 single quote
I am also writing here.
''';
// Multi Line Using Double Quotes
String otherMultiLineText = """
This is Multi Line Text
with 3 double quote
I am also writing here.
""";
// Printing Information
print("Multiline text is $multiLineText");
print("Other multiline text is $otherMultiLineText");
}
✅
: Strings are essential for text processing and user interface development!
In Dart, type conversion allows you to convert one data type to another type. For example, to convert String to int, int to String or String to bool, etc.
void main() {
String strvalue = "1";
print("Type of strvalue is ${strvalue.runtimeType}");
int intvalue = int.parse(strvalue);
print("Value of intvalue is $intvalue");
print("Type of intvalue is ${intvalue.runtimeType}");
}
Output:
Type of strvalue is String
Value of intvalue is 1
Type of intvalue is int
void main() {
int one = 1;
print("Type of one is ${one.runtimeType}");
String oneInString = one.toString();
print("Value of oneInString is $oneInString");
print("Type of oneInString is ${oneInString.runtimeType}");
}
✅
: Type conversion is essential when working with user input, which is always received as strings!
In Dart, boolean holds either true or false value. You can write the bool keyword to define the boolean data type. You can use boolean if the answer is true or false.
Consider the answer to the following questions:
These all are yes/no questions. It's a good idea to store them in boolean.
void main() {
bool isMarried = true;
print("Married Status: $isMarried");
}
Output:
Married Status: true
✅
: Booleans are perfect for representing binary states and conditions in your programs!
The list holds multiple values in a single variable. It is also called arrays. If you want to store multiple values without creating multiple variables, you can use a list.
void main() {
List names = ["Raj", "John", "Max"];
print("Value of names is $names");
print("Value of names[0] is ${names[0]}"); // index 0
print("Value of names[1] is ${names[1]}"); // index 1
print("Value of names[2] is ${names[2]}"); // index 2
// Finding Length of List
int length = names.length;
print("The Length of names is $length");
}
Output:
Value of names is [Raj, John, Max]
Value of names[0] is Raj
Value of names[1] is John
Value of names[2] is Max
The Length of names is 3
❌
: List index always starts with 0. Here names[0] is Raj, names[1] is John and names[2] is Max.
An unordered collection of unique items is called set in Dart. You can store unique data in sets.
void main() {
Set weekday = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
print(weekday);
}
Output:
{Sun, Mon, Tue, Wed, Thu, Fri, Sat}
✅
: Set doesn't print duplicate items - each value can only appear once in a set!
In Dart, a map is an object where you can store data in key-value pairs. Each key occurs only once, but you can use same value multiple times.
void main() {
Map myDetails = {
'name': 'John Doe',
'address': 'USA',
'fathername': 'Soe Doe'
};
// displaying the output
print(myDetails['name']);
}
Output:
John Doe
✅
: Maps are perfect for storing structured data like user profiles, configuration settings, or any key-value relationships!
In Dart, var automatically finds a data type. In simple terms, var says if you don't want to specify a data type, I will find a data type for you.
void main(){
var name = "John Doe"; // String
var age = 20; // int
var height = 5.9; // double
var isStudent = true; // bool
print(name);
print(age);
print(height);
print(isStudent);
}
Output:
John Doe
20
5.9
true
✅
: The var keyword is convenient for quick prototyping, but explicit types make your code more readable and self-documenting!
You can check runtime type in Dart with .runtimeType after the variable name.
void main() {
var a = 10;
print(a.runtimeType);
print(a is int); // true
}
Output:
int
true
✅
: Runtime type checking is useful for debugging and ensuring your variables have the expected types!
You may have heard of the statically-typed language. It means the data type of variables is known at compile time. Similarly, dynamically-typed language means data types of variables are known at run time. Dart supports dynamic and static types, so it is called optionally-typed language.
A language is statically typed if the data type of variables is known at compile time. Its main advantage is that the compiler can quickly check the issues and detect bugs.
void main() {
var myVariable = 50; // You can also use int instead of var
myVariable = "Hello"; // this will give error
print(myVariable);
}
Output:
Error:
A value of type 'String' can't be assigned to a variable of type 'int'.
A language is dynamically typed if the data type of variables is known at run time.
void main() {
dynamic myVariable = 50;
myVariable = "Hello";
print(myVariable);
}
Output:
Hello
❌
: Using static type helps you to prevent writing silly mistakes in code. It's a good habit to use static type in Dart.
✅
: Static typing provides better performance and catches errors at compile time!
Now it's time to practice what you've learned about data types in Dart!
Create a comprehensive Dart program that demonstrates the use of all data types we've learned.
Requirements:
❌
: Try to solve this exercise on your own before looking at the solution!
✅
: This exercise covers all the data types we've learned and shows how they work together!
Let's look at some common mistakes when working with data types and best practices to avoid them.
// ❌ Wrong
int age = "25"; // Error: String can't be assigned to int
// ✅ Correct
int age = 25;
// or
int age = int.parse("25");
// ❌ Wrong
String result = 10 + 20; // Error: int can't be assigned to String
// ✅ Correct
String result = (10 + 20).toString();
// ✅ Good
String name = "John";
int age = 25;
// ❌ Less clear
var name = "John";
var age = 25;
// ✅ Safe conversion
String numberString = "123";
int? number = int.tryParse(numberString);
if (number != null) {
print("Number: $number");
} else {
print("Invalid number");
}
✅
: Following these best practices will help you write more robust and maintainable Dart code!
Congratulations! You've completed the comprehensive Data Types in Dart Tutorial. Here's what you've accomplished:
var keyword and type inferenceTo expand your Dart knowledge, consider learning about:
✅
: You now have a solid understanding of all data types in Dart and are ready to build complex applications!
❌
: Remember to always choose the appropriate data type for your specific use case and handle type conversions safely!