While going through layout tutorial in flutter docs, I came across
margin: const EdgeInsets.only(top: 8.0),
What is the purpose of const here? e.g.
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(icon, color: color,),
Container(
margin: const EdgeInsets.only(top: 8.0), // <-------
)
],
);
It is useful when a widget does not need to be rebuilded because when a change is applied to one widget with setState the whole widget tree is rebuild, when const is used it will make your code faster...
An immutable set of offsets in each of the four cardinal directions. Typically used for an offset from each of the four sides of a box. For example, the padding inside a box can be represented using this class. The EdgeInsets class specifies offsets in terms of visual edges, left, top, right, and bottom.
const EdgeInsets.symmetric({double vertical: 0.0, double horizontal: 0.0 }) Creates insets with symmetrical vertical and horizontal offsets. Sample. Eight pixel margin above and below, no horizontal margins: assignment const EdgeInsets.symmetric(vertical: 8.0)
Padding widget in flutter does exactly what its name says, it adds padding or empty space around a widget or a bunch of widgets. We can apply padding around any widget by placing it as the child of the Padding widget.
const
is for compile time constant and is just an optimization.
Consts are canonicalized, no matter how often your app executes const EdgeInsets.only(top: 8.0)
there will always be ever a single instance.
Just EdgeInsets.only(top: 8.0)
(outside a const context where const
would be the default) or new EdgeInsets.only(top: 8.0)
would create a new instance every time this code is executed and also garbage collection would have to deal with it afterwards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With