How to use list generate in Dart

0
65590
How to use list generate in Dart

One of very handy utility in Dart is the ability to generate a list of values. In this article, I will show you how to use list generate in Dart and Flutter.

List generate in Dart and Flutter

In Dart, the core library provides an utility method to handle value generation for List data structure, since generation or making dummy data is a pretty common task. Here the definition:


List<E>.generate(
  int length,
  E generator(
    int index
  ), {
  bool growable: true
})

The first parameter is to specify the size of the list.

The second parameter is a generator function that produces list values.

However, it has bottleneck, because the generator for each index works in range from 0 to length - 1 in increasing order. Hence, we can either generate based on index value or we don’t use index of generator.

To make it practical, following are several examples to demonstrate.

1. Generate a list of numbers

This one will generate all numbers from 1 to 10.


new List<int>.generate(10, (i) => i + 1)

We can generate all square numbers.


new List<int>.generate(10, (i) => i * i)

2. Generate a list of dummy text

Take a simple use-case, you want to quickly mock the UI in Flutter app and need a dummy item list.


class Person {
  final String name;
  final String avatarUrl;

  Person({this.name, this.avatarUrl});
}

void main() {
  var dummyPersonList = new List<Person>.generate(20, (i) {
    return Person(
      name: 'John Doe',
      avatarUrl: 'http://somewebsite.com/dummy_avatar.jpg',
    );
  });
}

Then you can put this dummy list into listview widget to render.

Summary

It is simple and straight-forward to use list generate. Even though, it doesn’t work in all cases, it comes very handy in many situations.

You will need it sometimes. And don’t forget, it works in Dart and Flutter.