Search code examples
flutterdartstate-management

When do we need to rebuild the StatelessWidget?


In the Flutter job interviews, sometimes I am asked how we can rebuild the StatelessWidget and the answer to this is to call the markNeedsBuild() method of the widget's Element or BuildContext.

So the question is, are there any cases when we need to rebuild a StatelessWidget and it's better to use a StatelessWidget instead of the StatefulWidget?

I found cases where people wanted to rebuild the StatelessWidget, such as How to invoke a rebuild of a stateless widget?, but in all these cases it was better to use StatefulWidget or state management instead.


Solution

  • The whole purpose of the StatelessWidget is not to rebuild. If you require rebuild you have to use StatefullWidget.

    I guess the interviewers are trying to trick you xD

    Summary

    Stateless Widget:

    • Stateless Widgets are static widgets.
    • They do not depend on any data change or any behavior change.
    • Stateless Widgets do not have a state, they will be rendered once and will not update themselves, but will only be updated when external data changes.
    • For Example: Text, Icon, RaisedButton are Stateless Widgets.

    Stateful Widget:

    • Stateful Widgets are dynamic widgets.
    • They can be updated during runtime based on user action or data change.
    • Stateful Widgets have an internal state and can re-render if the input data changes or if Widget’s state changes.
    • For Example: Checkbox, Radio Button, Slider are Stateful Widgets