Home > Mobile >  About the benefits of const for Stateles widget in Flutter
About the benefits of const for Stateles widget in Flutter

Time:10-12

There is a custom appbar:

class _MyAppBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SliverAppBar(
      title: Text('Catalog', style: Theme.of(context).textTheme.headline1),
      ...
    );
  }
}

and usage of it

return Scaffold(
      body: CustomScrollView(
        slivers: [
          _MyAppBar(),
          const SliverToBoxAdapter(child: SizedBox(height: 12)),
          ...

In that code const using wildly (it's the Flutter team code as an example of a particular package usage) and why in this case const isn't used for _MyAppBar() (we could add const constructor in _MyAppBar definition)?

CodePudding user response:

When you create a widget and is able to prefix it with const that widget will not rebuild. The framework knows not to rebuild such widgets because it can tell that the objects did not change. Constant objects are resolved at compile-time, and due to a process known as canonicalization if two or more objects have the same parameters, and are constant, they will refer to the same instance.

For example, if you have

@override
Widget build() {
  const MyWidget();
}

And then somewhere you call setState, MyWidget will not be reconstructed because it was already resolved at compile-time, and the framework will also not call its build method which makes sense because non of the arguments passed to MyWidget (which are none here) has changed as a result of issuing the rebuild so the configuration is still the same.

Moreover if somewhere else you call const MyWidget(); you will still refer to the same object/instance so it's more optimal.

And they added the lint rule so that people add a const constructor and are able to invoke their widgets/classes with const and it uses by default in flutter. Flutter apps, packages, and plugins created with flutter create starting with Flutter version 2.3.0 are already set up to use the lints defined in this package.

Disabling individual rules

include: package:lints/recommended.yaml

linter:
  rules:
    avoid_shadowing_type_parameters: false
    await_only_futures: true

For more read this analysis option and const keyword.

After reading this, it would be helped you to understand why in your case const isn't used for _MyAppBar().

SRC From: remove const

CodePudding user response:

when you use const behind widgets it changes the way it is rebuilt it will not rebuild completely from scratch when you setState the widget.it uses the data that has been stored on ram and rebuilds it with that. when your widget does not change with rebuilding the page it is recommended to improve the application behavoiur

  • Related