class StudentModel {
final String name;
final String age;
StudentModel({required this.name, required this.age});
}
this is StudentModel class
I didn’t understand how the values will store in this List
class StudentModel {
final String name;
final String age;
StudentModel({required this.name, required this.age});
}
this is StudentModel class
I didn’t understand how the values will store in this List
4
Answers
You can follow the below code to add elements to your list.
studentDetails
is basically a list that contains n number ofStudentModel
objects. You can visualize it being the following form:You can use below code snippet for understanding
Here we created a object names
students
for storing a list of studentsin next line we are adding student details to list with
name
andage
keys (both keys arerequired
as mention in model)then we iterate the student list to print student details which we have added.
If you are talking about how this class constructor works then here is some explanation.
In flutter, when you are creating this type of class there are few ways to set value which depends how you created the constructor of data model class.
1. Named parameters
This type of parameters inside
{}
is called named parameters. To set these kind of values you need to specify the name of the parameter in which you want to set value like this.This will also allows you to setup the required parameters.
If you don’t want to use the name each time & simply want to set values then you can second approach.
2. Unnamed parameters
Here you can just remove the curly braces. Which allows you to set values like this.
3. Optional parameters
In both of above types you have to pass all the parameters because they are required as mentioned in 1st approach & second approach make them required by default.
But if you want to set some parameters as optional in both ways you can do this.
In named you can write like this
In unnamed you can try this
Hope this will help
List studentDetails = [];
The above code is used to initialize "empty" studentDetails list. Also, by declaring this every time you load this widget the list will be initialize as empty.
By add function you can add values to list
Ex. studentDetails.add(StudentModel(name: "Rishabh Gupta", age: "23")));