Dart 2.2之后如何设置文字

时间:2019-06-09 13:15:47

标签: dart literals

直到2.2,如何在Dart 2.2之后设置文字才支持Set文字。请随意发表评论。谢谢。

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

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

更新1

我可以将列表定义为一系列的define语句。但是,这似乎无效。

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;

}

在C语言中,我可以有效地定义结构,但我不知道如何在dart中实现。

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

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

更新2

谢谢jamesdlin的建议,我可以简化列表初始化并按索引访问元素。但是,它仍然不能像C语言一样有效。

 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 个答案:

答案 0 :(得分:3)

您使用{}指定Set(和Map)文字:

var mySet = {1, 2, 3};

请注意,为避免与Map文字产生歧义,创建空集时必须明确指定类型。例如:

var emptySet = <int>{};

另请参见https://dart.dev/guides/language/language-tour#sets

答案 1 :(得分:0)

只需将mosquitto{分别替换为}[,一切都会正常。