Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter widget or layout need add const?

For example, I have a Text Widget. When I insert (Alt+Insert) Padding, the value of the padding property is const EdgeInsets.all(8.0). I don't quite understand why const is added. If all Widgets are added with Widget, there will be performance. Upgrade? Is it like const Text('text')

@override
Widget build(BuildContext context) {
  return Padding(
    padding: const EdgeInsets.all(8.0),
    child: Text('text'),
  );
}
like image 779
da fa Avatar asked Feb 20 '26 10:02

da fa


1 Answers

In Dart, their are basically 3 different specifier. const, static and final, each quite different from the other.

Now, the thing with const is that the compiler tries to calculate the value of that variable while at compile time. So, if you have something like : const CONST_STRING = "String", then all the uses of CONST_STRING will be replaced by its value (ie "String"), by the compiler. This definitely provides a performance boost. But their is a point here. You cannot use const for everything, as it need to be accessible at the compile time.

So, you can definitely use primitive data types as const, but for objects, their constructor will have to support const (see the EdgetInset constructor).

Furthermore, to be able to make the constructor const, the class' member variables will have to be construct-able at compile time.

like image 86
zeekhuge Avatar answered Feb 27 '26 09:02

zeekhuge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!