Home > Software design >  How to fill a list with null values so it is a specific length?
How to fill a list with null values so it is a specific length?

Time:03-21

I have a situation where I have a list that can be at most 4 elements.

However, if I have only 1-3 elements to put in that list, how can I fill the remainder with null values?

For example, a List<int?> of length 4 with 2 given elements, should result in:

[1,3] -> [1,3,null,null]

Here's what I'm doing, but maybe there is a better way

 List.generate(4, (index) {
      try {
        final id = given.elementAt(index);
        return id;
      } catch (error) {
        return null;
      }
    });

CodePudding user response:

The simplest version would probably be:

[for (var i = 0; i < 4; i  ) i < given.length ? given[i] : null]

You can use List.generate, but in this case, the function is simple enough that a list literal can do the same thing more efficiently. (Or, as @jamesdlin says, if you want a fixed-length list, use List.generate).

A more indirect variant could be:

 List<GivenType?>.filled(4, null)..setAll(0, given)

where you create a list of four nulls first, then write the given list into it. It's probably just more complicated and less efficient.

  •  Tags:  
  • dart
  • Related