Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Role of Const in defining EdgeInsets in Flutter

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),  // <-------
      )
    ],
  );
like image 485
WitVault Avatar asked Jul 25 '18 08:07

WitVault


People also ask

Why const is used in flutter?

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...

What is EdgeInsets only in flutter?

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.

What is EdgeInsets symmetric?

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)

What is padding in flutter?

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.


1 Answers

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.

like image 150
Günter Zöchbauer Avatar answered Oct 01 '22 22:10

Günter Zöchbauer