【问题标题】:Is Const for creating Singleton Objects?Const 是用于创建单例对象吗?
【发布时间】:2021-07-26 00:50:13
【问题描述】:

来自Why does Dart have compile time constants?

Dart 有编译时常量的概念。编译时 常量在编译时被解析和创建,并被规范化。

例如,这里是 Point 的 const 构造函数:

class Point {
  final num x, y;
  const Point(this.x, this.y);
}

这是你如何使用它的:

main() {
  var p1 = const Point(0, 0);
  var p2 = const Point(0, 0);
  print(p1 == p2); // true
  print(p1 === p2); // true
}

这段代码 sn-p 来自 Stack Overflow 我正在重用这个很好的例子,再次感谢。 我注意到在颤振小部件中经常使用 Const。

这是否意味着我们可以使用const 来创建单例对象?

【问题讨论】:

    标签: dart


    【解决方案1】:

    要创建单例,请查看以下答案:How do you build a Singleton in Dart?

    constfinal 之间存在区别,可以在这里找到:What is the difference between the "const" and "final" keywords in Dart?

    但简而言之,您不能将const 用于单例对象,因为该对象不是编译时常量。您需要使用final

    【讨论】:

    • 非常感谢您的有用回复,不胜感激。我不知道这一点,尤其是当您将列表声明为 final 并且您仍然可以对其附加值但是当它标记为 const 时您甚至无法添加新值:几乎就像 final 就像 javascript 中的 const 而 const 是真正的 const那是小姐杜松子酒 javascript
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 2019-06-17
    相关资源
    最近更新 更多