Generics Class in Dart
Generics In Dart
They are same as the dart collection. In dart, you used the different collections to store the group of data.
Example
void main()
{
List list = ["Nabin", 19.0, 7500];
print(list);
}
Generics are the way of supporting the type-safety for all the Dart collections. The angular bracket is used to declare the generics in dart where the angular bracket is placed after the collection type which holds the data type which you want to enforce that collection to hold.
Syntax
CollectionName<dataType> variableName = CollectionName();
Info
Note: Generics can be used for all the collection types, here is an example of generics for some of the common collections used in dart.
Example Of Generics List
class College {
List<String> studentsName = [
"Suraj Subedi",
"Rahul Jaishwal",
"Sachin Khand"
];
void printAllStudentName() {
for (var i in studentsName) {
print(i);
}
}
}
void main(List<String> args) {
var college = College();
college.printAllStudentName();
}
Example Of Generics Set
class College {
//set only contains distict value, ingnores the duplicate data
Set<String> studentsName = {
"Suraj Subedi",
"Rahul Gautam",
"Mahan Gurung",
"Suraj Subedi",
};
void printAllStudentName() {
for (var i in studentsName) {
print(i);
}
}
}
void main(List<String> args) {
var college = College();
college.printAllStudentName();
}
Example Of Generics Map
class College {
//map holds data in key-value pair
Map<int, String> studentsName = {
20048: "Suraj Subedi",
25412: "Rahul Gautam",
56557: "Mahan Gurung",
41245: "Sameen Kunwar",
};
void printAllStudentName() {
studentsName.forEach((key, value) {
print("Key:$key, value: $value");
});
}
}
void main(List<String> args) {
var college = College();
college.printAllStudentName();
}