简体   繁体   中英

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

I am new to flutter and confused with it's constructor.

For example:

  • sample 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:
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.

Is there any potential risk in sample 2?

You would use a const constructor when you dont want this widget to be rebuild. A constant widget is like the constant pi, it won't change. If you have state however you want to use the normal constructor in Sample 2, because the widget changes and cant be constant then.

So you get a slight performance increase when you use const in places where it makes sense (because it wont be rebuild).

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 .
  • You can't define const inside a class . But you can in a function .
  • For Flutter specific, everything in the build method won't be initialized again when the state is updated.
  • const can't be changed during runtime.

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,

try giving unconstant values to const Constuctor to see the difference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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