Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For which flutter widgets we need to use const?

Tags:

flutter

dart

I understand the benefits of const and the widgets will not rebuilt on state change, but still it's so obvious when you see below code that they are constants and I was hoping flutter handled it automatically. Or, flutter is taking care of it already and I am unaware?

// This makes sense to me but with above mentioned concern 
const Text('Your Text Here')
const Icon(Icons.chevron_right, size: 20.0),

Anyhow, my question is: Is it fine to define SizedBox & EdgeInsets widgets as constants(const) as it defined below?

Padding(
  padding:
      const EdgeInsets.only(top: 16.0, right: 6.0, bottom: 16.0, left: 16.0),
  child: Row(
    children: <Widget>[
      const SizedBox(width: 16.0),
      const Icon(Icons.chevron_right, size: 20.0),
    ],
  ),
),
like image 869
Syed Avatar asked Nov 28 '19 06:11

Syed


1 Answers

Basically flutter trying to update some widgets in tree, and if it const, nothing to update. Here you can find explanation. https://dev.to/pedromassango/flutter-performance-tips-1-const-constructors-4j41

You need to know one an important thing, that if you changed widget in a tree, everything after this widget will be removed and redrawed(not updated). So, if you define it as const, nothing will be removed. And that is OK(answer on you question) Also I recommend to read how flutter rebuild screen and update widgets: https://www.didierboelens.com/2019/09/flutter-internals/

And the last great article about performance https://api.flutter.dev/flutter/widgets/StatefulWidget-class.html#performance-considerations

like image 99
Yauhen Sampir Avatar answered Oct 06 '22 01:10

Yauhen Sampir