user3249027
user3249027

Reputation: 542

Correct way to type Lists (or anything) in Dart (Flutter)

How "deep" should one type? F.e:

List<List<Map<int, List<int>>>> - looks kind of strange and hard to read, but possible. Why is it, that I never see typings like this?

I can't find any information about this so I have a feeling that it's wrong or unusual, but it'd be great if someone could elaborate.

Upvotes: 0

Views: 258

Answers (2)

Tokenyet
Tokenyet

Reputation: 4291

That's logically right to use It, but unreadable for anyone including you. So let's recall the format here:

List<
  List<
    Map<int, List<int>>
  >
>

The deepest and smallest unit is Map<int, List<int>>, It's a bit ugly, but you could still use this. However you need a List for this ugly unit, so you should give It a class to make It more sense.

class Round {
  Map<int, List<int>> monsterIdPerRound; // <round 1, monster 0, 1, 2, 0, 3...>
}

And the code could be:

List<
  List<Round>
>

-

Do you satisfy with this? If not we could make It much more sense as below:

// FightManager, arrange the fight with a lot of predefined round of fights.
class FightManager {
  List<Round> rounds;
}

Now, the code should be:

List<FightManager>

-

This is easy to maintain, If you ask what is the List<FightManager>? It's still a same way to give It a meaning.

class LevelManager {
  List<FightManager> fightManagers;
  LevelManager(this.fightManagers);
}

--

List<FightManager> fightManagers = new List<FightManager>();
// prepare datas...
fightManager.add(getSwordOnlyFightManager());
fightManager.add(getMagicOnlyFightManager());
fightManager.add(getArcherOnlyFightManager());
fightManager.add(getBossFightManager());
fightManager.add(getRandomFightManager());

LevelManager(fightManagers);

It's time to go back to the original format, and ask what code do you want to maintain or keep coding?

List<
  List<
    Map<int, List<int>>
  >
>

or

LevelManager

Hope you don't mind I made a game example for explaining the code.

Upvotes: 1

RoyalGriffin
RoyalGriffin

Reputation: 2007

You don't see typings like this, because it is highly unusual. You can go deeper too if you want to. If you need to define a variable like that, it is highly probable that you are doing something wrong and what you want to achieve can be done in a simpler way.
For the variable you have defined, you'd have to imagine a use case like:
A list of schools in a state(List<List<Map>>) having a list of multiple schools(List<Map>)(Let say each city has multiple schools) having a map of multiple classes/batches{(A school)(Map<int, List<int>>)} of students' role numbers(List<int>).
^Read it from bottom to top if you have difficulty imagining.
You'd usually see a table for storing such kind of data structure and not a flat variable. More so, while developing UI for an application.

Upvotes: 0

Related Questions