List of tuples in flutter/dart

Viewed 18072

I would like to have a list of tuples in dart/flutter, loop over them and read the first and second variable. There is a pub.dev package that creates a tuple in flutter. Is there another way in dart? Do I need to use a class to create a tuple like the flutter package does?

I began to create an example in dart pad

void main() {
  List testList = [("a",1),("b",2),("c",3),("d",4),("e",5)];
  
  
  for (var i = 0; i < 5; i++) {
    print('hello $i');
    currentItem = testList[i];

  }
}
2 Answers

Example of how you can iterate over your data pairs by using a Map as data structure:

void main() {
  final testMap = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5};

  for (final mapEntry in testMap.entries) {
    final key = mapEntry.key;
    final value = mapEntry.value;

    print('Key: $key, Value: $value');
    // Key: a, Value: 1
    // Key: b, Value: 2
    // Key: c, Value: 3
    // Key: d, Value: 4
    // Key: e, Value: 5
  }
}

You can also rather easy introduce your own Pair class which allows you to bind two objects together:

class Pair<T1, T2> {
  final T1 a;
  final T2 b;

  Pair(this.a, this.b);
}

void main() {
  final testList = [
    Pair("a", 1),
    Pair("b", 2),
    Pair("c", 3),
    Pair("d", 4),
    Pair("e", 5)
  ];

  for (final pair in testList) {
    print('${pair.a} -> ${pair.b}');
  }
  // a -> 1
  // b -> 2
  // c -> 3
  // d -> 4
  // e -> 5
}

In most cases I will recommend you to make a class for you specific need since it makes it easier to make type safe code.

If you want to use package:tuple, you could do:

void main() {
  var testList = <Tuple2<String, int>>[
    Tuple2("a", 1),
    Tuple2("b", 2),
    Tuple2("c", 3),
    Tuple2("d", 4),
    Tuple2("e", 5),
  ];
  
  for (var tuple in testList) {
    print('current tuple: (${tuple.item1}, ${tuple,item2})');
  }
}
Related