[英]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 中的const
和key
,并且 sample1 和 sample2 都运行良好。
样本 2 是否存在潜在风险?
当您不希望重建此小部件时,您将使用 const 构造函数。 常量小部件就像常量 pi,它不会改变。 如果您有 state 但是您想使用示例 2 中的普通构造函数,因为小部件会发生变化并且不能保持不变。
因此,当您在有意义的地方使用 const 时(因为它不会被重建),您会获得轻微的性能提升。
关键属性是另一个主题。
常量
const
关键字的变量在compile-time
初始化,并且在runtime
已经赋值。class
中定义const
。 但是您可以在function
中。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.
当您将 const 与构造函数一起使用时,它是编译时常量,并且构造函数中给出的所有值都必须是常量,
尝试为 const 构造函数提供非恒定值以查看差异
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.