How to set literals after Dart 2.2

不问归期 提交于 2020-04-13 08:01:15

问题


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));

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/56514894/how-to-set-literals-after-dart-2-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!