Syed
Syed

Reputation: 16523

Should "const" for widgets need to be used only in stateful widgets?

It's clear that in StatefulWidget if state changes then const Text('...') will not be rebuild.

class _SomeWidgetState extends State<SomeWidget> {
  @override
  Widget build(BuildContext context) {
    return const Text('Some Static Text'); // doesn't rebuild
  }
}

But, my question is: Is there any benefits of using const in StatelessWidget?

class ListItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const Text('Some Static Text') // Is `const` useful here?
  }
}

Upvotes: 2

Views: 2802

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277567

Yes, it is useful.

Const constructors inside build is useful for all kinds of widgets, including StatelessWidget and other less common ones like InheritedWidget or RenderObjectWidget.

Bear in mind that all widgets may take parameters, so you may have:

class MyStateless extends StatelessWidget {
  const MyStateless({Key key, this.count}): super(key: key);

  final int count;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text('$count'),
        const Text('static text'),
      ],
    );
  }
}

In that situation, your stateless widget may rebuild with a different parameter, like going from:

MyStateless(count: 0);

to:

MyStateless(count: 42);

In that situation, using const Text('static text') will not cause this text to rebuild.

Upvotes: 6

Related Questions