Home > Software design >  What's the most and the least expensive Widgets to build in flutter
What's the most and the least expensive Widgets to build in flutter

Time:09-14

in my case I need to set a widget in a column under a condition simply see :

isSomeBool ? MyWidget() : thatLeastExpensiveWidget()

I can use just SizedBox or Container simply, but are they the least expensive widgets in flutter that we can use or is there any widget made for this purpose only

and I'm interested to know also what's the most expensive widget that flutter can build

Thanks

CodePudding user response:

You can only render the part you need using just the if statement and avoid rendering the else part as shown below.

child: Column(children: [
    ListTile(
      ...
    ),
    if (bool)
      Container(
        ...
      ),
  ])

CodePudding user response:

I don't know which is least expensive because it makes you dive deep into source code of Flutter, who could answer you is the one that make/contribute this Flutter framework. But SizedBox & Container are simplest widget so maybe it is simplest as far as I know. StatelessWidget also cheaper than StatefulWidget. By the way, if you want to build your own widget, use class StatelessWidget instead of method like Widget _buidYourOwnWidget() because method reload each time app screen is rebuilt. In this case, class StatelessWidget is cheaper than method _buidYourOwnWidget().

About what is most expensive, there are 2 kinds of expensive: about time or about space. About time, obviously is Future, because it can delay any how long you want. About space, it is your custom widget - because a widget may contain many children widget. Example, Scaffold is entire a screen, so it is most expensive about space.

CodePudding user response:

I would recommned SizedBox instead Container to add whitespace to a layout.

A Container is a heavier Widget than a SizedBox, and as bonus, SizedBox has a const constructor. reff

It is effectively the same. If you only use Container for width/height there might be a very minor minor negligible performance overhead. but you most certainly will not be able to measure it. reff

This is another way i ussually use by using list.

Column(
 children:[
  // other widget here

  // three dots is to add item to the list
  ...isSomeBool  ? [ my widget ] : []
  // if false => this will add empty list to the children, so nothing rendered.
  // but idk about calculation behind the list. 
 ]
)

CodePudding user response:

dart supports conditional inclusion of elements in a list, so you don't need a dummy Widget, just like this for example:

Column(children: [
  Container(),
  Container(),
  Container(),
  Container(),
  if (isSomeBool) MyWidget(),
  Container(),
  Container(),
  Container(),
  Container()
]);
  • Related