const 构造函数和 no_const 构造函数有什么区别?

What's the difference between const constructor and no_const constructor?

我是 flutter 的新手,对它的构造函数感到困惑。

例如:

class MyContainer extends StatelessWidget {
  final Color color;
  const MyContainer({Key key, this.color}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
    );
  }
}
class MyContainer extends StatelessWidget {
  final Color color;
  MyContainer({this.color});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: color,
    );
  }
}

我删除了示例 2 中的 constkey,并且示例 1 和示例 2 都运行良好。

样本2是否存在潜在风险?

当您不想重建此小部件时,您可以使用 const 构造函数。 常量小部件就像常量 pi,它不会改变。 如果你有状态但是你想使用示例 2 中的普通构造函数,因为小部件会改变并且不能保持不变。

所以当你在有意义的地方使用 const 时,你会得到轻微的性能提升(因为它不会被重建)。

关键属性是另外一个话题。

当const与构造函数一起使用时,它是编译时常量,构造函数中给定的所有值都必须是常量,

尝试给 const 构造函数赋予不恒定的值以查看差异

const

  • 具有 const 关键字的变量在 compile-time 处初始化 并且在 runtime.
  • 时已经分配
  • 您不能在 class 中定义 const。但你可以在 function.
  • 对于 Flutter 特定的,build 方法中的所有内容都不会 状态更新时再次初始化。
  • const 无法在运行时更改。

什么时候使用const?

-

Use const: If you are sure that a value isn’t going to be changed when running your code. For example, when you declare a sentence that always remains the same.