飞镖的构造函数 [英] Constructors in dart

查看:103
本文介绍了飞镖的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课堂上有这个构造函数。现在,这样的话,我得到

I have this constructor in my class. Now when it's like this, I get

The type parameter icon is annotated with @required
but only named parameters without default value can be annotated with it.

-

const Category(
    @required this.name,
    @required this.icon,
    @required this.color
  ) : assert(name != null),
      assert(icon != null),
      assert(color != null);

当调用这样的构造函数时:

And when calling the constructor like this:

        Category(name: _categoryName, icon: _categoryIcon, color: _categoryColor),

这是一个错误。

当我用{}包围构造函数参数时,所有这些都消失了。

All of this goes away when I surround my constructor arguments with {}.

这是什么意思?

推荐答案

{} 缺少为它们命名的参数

{} are missing to make them named parameters

const Category({
    @required this.name,
    @required this.icon,
    @required this.color
  }) : assert(name != null),
      assert(icon != null),
      assert(color != null);

或仅删除 @required

不带 {} 的位置参数,无论如何都是必需的。

Without {} they are positional parameters which are required anyway.

Category('foo', someIcon, Colors.white)

vs

Category(name: 'foo', icon: someIcon, color: Colors.white)

[] 使它们成为可选的位置参数。

[] makes them optional positional parameters.

需要首先声明位置(非可选),最后是可选参数。

Positional (non-optional) need to be declared first, optional parameters come at the end.

可选的位置参数和可选的命名参数不能一起使用。

Optional positional and optional named parameters can not be used together.

可选的参数(位置和命名参数)可以具有默认值

Optional parameters (positional and named) can have default values

this.name = 'foo'

默认值必须是编译时常量。

Default values need to be compile-time constants.

这篇关于飞镖的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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