Reputation: 733
I am new to Flutter and Dart. I am trying to create long List View in Flutter. but I am stuck with this Constructor
. Can anyone explain how this Constructor works?
List<String> = List<String>.generate(1000,(counter) => "Item $counter");
Upvotes: 6
Views: 37997
Reputation: 4779
List.generate
is very useful in terms of generating test data.
For e.g.
List<Student> getStudents({required int numOfStudents}) {
return List.generate(
numOfStudents,
(index) => Student(
id: '$index',
firstName: 'FName$index',
lastName: 'LName$index',
),
);
}
It can be fully randomized by using
List.generate(random.nextInt(3), (index) => Student(
id: '$index',
firstName: 'FName$index',
lastName: 'LName$index',
))
Upvotes: 2
Reputation: 149
List.generate
can be very useful if you know the length and structure of the list you like to create.
For example: You can create a List of maps too
Here generating a list with day e.g Mon, Tue,Wed,etc.. for the whole week see the 7 as the number of iterations.
final myList = List.generate(7, (index) {
final dateFormatted =DateTime.now().subtract(Duration(days:index));
return {
'day':DateFormatted.E().format(dateF),
'date':dateFormatted,
};
});
print(myList);
Upvotes: 2
Reputation: 1069
List<String> = List<String>.generate(1000,(counter) => "Item $counter");
this will generate 1000 item and you can manipulate each item threw your arrow function that takes counter as a parameter in that case counter will be ur index each time . the output will be :
"Item 0"
"Item 1"
"Item 2"
...
"Item 999"
Upvotes: 6
Reputation: 277137
The following:
List<String>.generate(1000,(counter) => "Item $counter");
will generate a List
of 1000 items, where each item are in order:
"Item 0"
"Item 1"
"Item 2"
...
"Item 999"
Upvotes: 18