简体   繁体   English

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

[英]What's the difference between const constructor and no_const constructor?

I am new to flutter and confused with it's constructor.我是 flutter 的新手,并且对它的构造函数感到困惑。

For example:例如:

  • sample 1:样品 1:
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,
    );
  }
}
  • sample 2:样本 2:
class MyContainer extends StatelessWidget {
  final Color color;
  MyContainer({this.color});

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

I removed const and key in sample 2, and both of sample1 and sample2 work well.我删除了示例 2 中的constkey ,并且 sample1 和 sample2 都运行良好。

Is there any potential risk in sample 2?样本 2 是否存在潜在风险?

You would use a const constructor when you dont want this widget to be rebuild.当您不希望重建此小部件时,您将使用 const 构造函数。 A constant widget is like the constant pi, it won't change.常量小部件就像常量 pi,它不会改变。 If you have state however you want to use the normal constructor in Sample 2, because the widget changes and cant be constant then.如果您有 state 但是您想使用示例 2 中的普通构造函数,因为小部件会发生变化并且不能保持不变。

So you get a slight performance increase when you use const in places where it makes sense (because it wont be rebuild).因此,当您在有意义的地方使用 const 时(因为它不会被重建),您会获得轻微的性能提升。

The key property is another topic.关键属性是另一个主题。

const常量

  • A variable with the const keyword is initialized at compile-time and is already assigned when at runtime .带有const关键字的变量在compile-time初始化,并且在runtime已经赋值。
  • You can't define const inside a class .您不能在class中定义const But you can in a function .但是您可以在function中。
  • For Flutter specific, everything in the build method won't be initialized again when the state is updated.对于 Flutter 特定的,当 state 更新时,构建方法中的所有内容都不会再次初始化。
  • const can't be changed during runtime. const在运行时不能更改。

When to use 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.

when you use const with constructor, it is compile time constant and all values given in constructor must be constant,当您将 const 与构造函数一起使用时,它是编译时常量,并且构造函数中给出的所有值都必须是常量,

try giving unconstant values to const Constuctor to see the difference尝试为 const 构造函数提供非恒定值以查看差异

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM