Home > Net >  Flutter List.generate editor bug
Flutter List.generate editor bug

Time:11-30

If we create a 2d/3d list by this way:

  List recipes = List.generate(
      999,
      (i) => List.generate(
          999,
          (i) => List<Ingredient>.filled(
              0,
              Ingredient(
                  name: '',
                  carbohydrates: 0,
                  proteins: 0,
                  lipids: 0,
                  fibers: 0),
              growable: true)));

Please assume that Ingredient is a simple Class.

When we try to access it:

print(recipes[0][0][0].name);

Arriving at this point:

print(recipes[0][0][0].

We need to see (access) the Class properties (like kcal, name, carbohydrates...); exactly as in a one dimension list.

However, at least in VS Code, the code editor display this only: hashCode, runtimeType, toString(), noSuchMethod(...)

When I try to create the list by this way:

List<List<List<Ingredient>>> ingredient =
      List.generate(999, (index) => [[]], growable: true); 

This bug does not exists, but I have no idea on how to fill (give a dimension and class) the first and the second list...

My first goal is not to lose the autocomplete function (by the editor) because it's too hard to remember every List.properties/funcions by mind.

The Ingredient Class:

class Ingredient {
  String? name;
  int? kcal;
  int? carbohydrates;
  int? proteins;
  int? lipids;
  int? fibers;

  Ingredient(
      {this.name,
      this.kcal,
      this.carbohydrates,
      this.proteins,
      this.lipids,
      this.fibers});
}

CodePudding user response:

You can use var or final, and it'll automatically know type of list from assigned value. But explicitly writing only a List will not work.

var ingredient = (List.generate( 
      999,
      (i) => List.generate(
          999,
          (i) => List<Ingredient>.filled(
              1, // -> put 1 if you want to populate your list or else it will be empty list
              Ingredient(
                  name: '',
                  carbohydrates: 0,
                  proteins: 0,
                  lipids: 0,
                  fibers: 0),
              growable: true))));

  print(ingredient[0][0][0]);
  print(ingredient[0][0][0].carbohydrates);

CodePudding user response:

Found the correct way (and tested). I leave it here as for other people:

  List<List<List<Ingredient>>> ingredient = (List.generate(
      999,
      (i) => List.generate(
          999,
          (i) => List<Ingredient>.filled(
              0,
              Ingredient(
                  name: '',
                  carbohydrates: 0,
                  proteins: 0,
                  lipids: 0,
                  fibers: 0),
              growable: true))));

The editor works as expected and the List is really multi dimensional and iterable.

This type of list is:

List[int][int][Ingredient(int)].classProperties

  • Related