Please see the question above. I looked the documents, but didn't find any answers.
CodePudding user response:
It depends on the child/ children if they don't have static value it can't be const. if the have hardcoded or static values then it must be const
CodePudding user response:
Why do we need to use const widgets in flutter?
It is recommended to use const constructors whenever possible when creating Flutter widgets. The reason is the performance increase since Flutter can save some calculations by understanding that it can reuse that widget from a previous redraw in the current one since it is a constant value.
Flutter has a special treat for when the instance of a widget doesn't change: it doesn't rebuild them.
Consider the following:
Foo( child: const Bar( child: Baz() ), )
In the case of the build method being called again (setState, parent rebuild, Inheritedwidget...), then due to the const for Bar subtree, only Foo will see its build method called.
The bar will never get rebuilt because of its parent because Flutter knows that since the widget instance didn't change, there's nothing to update.
Why can't we make a Container widget and Column widget const?
You cannot make const a Container as the Constructor of Container is not const that's why it won't let you do it.
This is allowed in the form of making the children const. Allowing const on the children means they will not rebuild if they are not dynamic.
Flutter doesn't rebuild widgets that are marked created through const constructor and the main part of the flutter widgets supports const constructors. Except for Column and Row and other multi-child layout widgets.
Do we really need to make multi-child layout widgets const?
The Column/Row themselves do not need to be const as they're only for laying out the widgets, it's the children that need to const. The same behavior applies to the rest of the Multi child layout widgets.
CodePudding user response:
These might be for lots of reasons. Instead of listing all of them here. I will show you how to explore each one of them on your own so that you can orient your investigations based on your needs. Below, are the steps I went through to figure out why the container is non-const. (you can do this with any other Widget or constructor)
Explore the source code
- Open the fuller package (in VSCode): [flutter_location]/packages/flutter/lib/src/widgets/container.dart
- Run
flutter pub get
- Look for the
Container
constructor - Add the
const
keyword in front of it - All elements that prevent the
Container
from being aconst
constructor, quite a few, will show errors!
To explore multiple widgets at once just open the entire folder [flutter_location]/packages/flutter. Then run
flutter pub get
.