Search code examples
listflutterdarttyping

How to 'multitype' fixed-order, fixed-length list in Dart


In my Flutter project, I have enabled the lint package. Somewhere in my code, I have a map Map<String, List<dynamic>> options = ...;. The List is typed as dynamic, but in fact it is always a non-growable, length 2 list [String, IconData]. I use map as follows:

options.entries
    .map((e) => SwitchListTile(
          title: Text(e.value[0].toString()),
          secondary: Icon(e.value[1]),
          value: notificationSettings[e.key],
          onChanged: (bool value) => onNotificationChanged(topic: e.key, enabled: value),
        ))
    .toList());

I.e. the String in the list is the title of the listTile, the IconData is the icon to show, and the map keys are given to the notificationSettings to fetch the current setting, as well as to the onNotificationChanged handler that updates the setting.

The linter says that I shouldn't use dynamic variables at the places where I used e.value[i], so I was wondering if a non-growable, fixed-type list could be typed explicitly, e.g. by writing something like List<String, IconData>. I have tried some intuitive syntaxes, but none work, and I can't find anything on the internet.


Solution

  • Dart does not support tuples right now but it is being discussed.

    For now, you should either create a class specific for your pair of data like this (please give it a better name which describes the purpose :) ):

    class StringIconDataRelation {
      final String string;
      final IconData iconData;
    
      const StringIconDataRelation(this.string, this.iconData);
    }
    

    Alternative, you can make a generic Pair class which can be used in your project:

    class Pair<T1, T2> {
      final T1 a;
      final T2 b;
      
      const Pair(this.a, this.b);
    }
    

    You can then have your options to have the type Map<String, Pair<String, IconData>>.

    In general, it is often recommended to create specific classes for relations since it can be made the code more clear and you can implement other relevant methods. But if it is for simple stuff, it is often not a problem to use a Pair class.

    You can also find a lot of packages on pub.dev which gives you tuples of different dimensions.