How to set literals after Dart 2.2

Viewed 6560

Set literals were not supported until 2.2, How to set literals after Dart 2.2. Please feel free to comment. Thank you.

class item_t {
  String name;
  int weight;
  int value;
}

main() {
  const List<item_t> items = [
    {'map', 9, 1}, // reports errors
  ];
}

update 1

I could define the list as a serial of define statements. However, it seems it is ineffective.

class item_t {
  String name;
  int weight;
  int value;
}

main() {
  // final item_t items = new item_t(100);
  List<item_t> items = new List(2);

  items[0].name = 'map';
  items[0].weight = 9;
  items[0].value = 1;

}

In C language, I can define a structure effectively but I don't know how to do that in dart.

typedef struct {
    char *name;
    int weight;
    int value;
} item_t;

item_t items[] = {
    {"map",                      9,   150},
    {"compass",                 13,    35},
    {"water",                  153,   200},
};

update 2

Thank you jamesdlin's advise, I can simplify the list initialization and access the element by index. However, it still can't be as effective as C language.

 var mySet = [
    {"map", 9, 150},
    {"compass", 13, 35},
    {"water", 153, 200},
    {"sandwich", 50, 160},
    {"glucose", 15, 60},
    {"tin", 68, 45},
    {"banana", 27, 60},
    {"apple", 39, 40},
    {"cheese", 23, 30},
    {"beer", 52, 10},
    {"suntan cream", 11, 70},
    {"camera", 32, 30},
    {"T-shirt", 24, 15},
    {"trousers", 48, 10},
    {"umbrella", 73, 40},
    {"waterproof trousers", 42, 70},
    {"waterproof overclothes", 43, 75},
    {"note-case", 22, 80},
    {"sunglasses", 7, 20},
    {"towel", 18, 12},
    {"socks", 4, 50},
    {"book", 30, 10}
  ];

  print(mySet[0].elementAt(1));
2 Answers

You use { and } to specify Set (and Map) literals:

var mySet = {1, 2, 3};

Note that to avoid ambiguity with Map literals, you must explicitly specify a type when creating an empty set. For example:

var emptySet = <int>{};

Also see https://dart.dev/guides/language/language-tour#sets

Just replace { and } with [ and ], respectively, and everything will work fine.

Related