如何在Dart 2.2之后设置文字 [英] How to set literals after Dart 2.2

查看:73
本文介绍了如何在Dart 2.2之后设置文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
  ];
}

更新1

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

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;

}

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

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},
};

更新2

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

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

推荐答案

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

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

var mySet = {1, 2, 3};

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

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

var emptySet = <int>{};

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

这篇关于如何在Dart 2.2之后设置文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆