I need a multidimensional array/list (2 and/or 3 dimensions) which must contains different objects.
This is what I found:
List recipes = List.generate(
999,
(_) => List<Ingredient>.filled(
9,
Ingredient(
name: '', carboidrates: 0, proteins: 0, lipids: 0, fibers: 0),
growable: true));
My needs is to have recipes[index/int][index/Ingredient].somethingoftheIngredientClass
As for example, if I create a single List:
List<Ingredient> recipe = <Ingredient>[];
I can access the class as
recipe[0].carboidrates
Not the same for my 2 dimensional list:
recipes[0][0].doesnotshowCarboidrates
3
Answers
Just found a programming 'bug'.
I tried to replicate my exactly code:
As you can see by adding 'Cheesecake' as the name.
In Init functions I just tried this:
This work as expected, I accessed the value correctly...
Console Output:
Really don't know why when I arrive at this point:
Visual Studio Code does not show Class/Ingredient properties*, however it works!
*It shows only:
Really hope someone should explain why...
A list or multi-dimensional lists can only have a single type. Looking at your sample code, it looks like you’re trying to associate ingredients and properties of a given recipe to a recipe using a multi-dimensional list.
A better approach would be to use classes. Classes will give you a more structured design and a little more flexibility. For example, the code below overrides the equality operator (
==
) andhashCode
to be able to compare recipes and find a given recipe in a list.If for whatever reason you wanted to associate a recipe with a list of recipes (e.g. similar recipes) I would use a
map
ofRecipe
toList<Recipe>
.Hope that helps!
Yup, another practical way to have 2d/3d list:
eg a 3d example:
On Init function:
And now when I arrive here:
I finally should see the Ingredient Class properties (like name, carboidrates… and so on!)… WIN!