dart:将类构造函数标记为const的含义是什么

标签 dart

所以我看到这样的代码:

class Whatever {
  final String name;
  const Whatever(this.name);
}

通过使用const标记构造函数这一事实会发生什么变化?它有什么作用吗?

我读过这样的话:

Use const for variables that you want to be compile-time constants. If the const variable is at the class level, mark it static const. (Instance variables can’t be const.)



但是对于类构造函数似乎没有意义。

最佳答案

  • 构造函数不能具有构造函数主体。
  • 所有成员都必须是最终成员,并且必须在声明时或通过构造函数参数或构造函数列表进行初始化。
  • 您可以使用此类的实例,其中仅允许使用常量(注释,可选参数的默认值,...)
  • 您可以创建常量字段,例如static const someName = const Whatever()

  • 如果该类没有const构造函数,则不能用于初始化常量字段。我认为在构造函数中指定它是有意义的。您仍然可以在运行时使用new Whatever()创建实例或添加工厂构造函数。

    也可以看看
  • Dartlang const constructor - how is it different to "regular" constructor
  • Dart factory constructor - how is it different to “const” constructor
  • How to make a factory constructor that returns as const value
  • Why does Dart have compile time constants?
  • How to write abstract class constructors so that it will be flexible for extending in sub classes

  • “旧样式”(仍然有效)枚举是如何使用const的一个很好的例子
    https://stackoverflow.com/a/15854550/217408

    关于dart:将类构造函数标记为const的含义是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28982231/

    相关文章:

    android - 如何为测试人员正确构建 apk?

    android - 在 Android Studio 中构建文件时出现 Flutter 错误

    xcode - slider 内 flutter 图像未出现

    dart - 发生异常。错误状态 : Future already completed in flutter listview and Video player

    dart - CSS不会应用在组件模板中

    flutter - 如何防止指标点在Chart_flutter中的setState()上消失

    android - 在 flutter 应用程序中集成 API 会出现错误 "Program linking failed"

    dart - 是否可以在动态创建的元素上使用querySelector()?

    flutter - 如何在 Flutter 中为小部件添加边框?

    flutter - 如何根据Flutter中的子项更改容器的高度?