Introduction
In this blog, we will look into the Dart Type System. When debugging code at compile time, the Dart Type System is quite useful. If the static and dynamic type checking of a particular variable produces different data types, it will throw an error, which is quite helpful while debugging the program. If you are new to Dart and are yet to set up your environment for the language, you can check out this article.
Dart Type System
Dart is a safety-enabled language that combines static and dynamic type checking at compile time to match the value of a variable to its data type. Sound typing is another name for this. Because of the type interference, data type annotations are optional, even though the types are required.
Adding type annotations to generic classes can fix all kinds of static problems. The following are some of the most commonly used generic collection classes:
- List
- Map
Example
The below code will throw an error while printing the list:
void printList(List<int> l) {
// Printing the list
print(l);
}
// Main function to run the program
void main() {
// Initialising a list
List l = [];
// Adding an integer value to the list
l.add(1);
// Adding a string value to the list
l.add("Red");
// Adding a float value to the list
l.add(3.4);
// Calling the print function to print the list
printList(l);
}
Output:
The argument type 'List<dynamic>' can't be assigned to the parameter type 'List<int>'
The above code throws this error because the function expects a list of integer datatype. But the list passed to the function contains elements of different data types.
One of the methods to remove the above error is to remove the int data type from the list in the printList function. For example,
void printList(List l) {
// Printing the list
print(l);
}
// Main function to run the program
void main() {
// Initialising a list
List l = [];
// Adding an integer value to the list
l.add(1);
// Adding a string value to the list
l.add("Red");
// Adding a float value to the list
l.add(3.4);
// Calling the print function to print the list
printList(l);
}
Output:
[1, Red, 3.4]




