How to dispose/recreate a Widget after an action

You will have to wrap your red icon in a StatefulWidget if you want to be notified when it is initialized and disposed. A StatelessWidget doesn't have these callbacks.

You can replace the StatefulWidget with null in a setState and its State will be disposed. You can set it back to normal in a second setState callback, and a new State will be created and its initState will be called.

If you want to dispose and initState without going through the intermediate step of having a widget be replaced with null, try giving your StatefulWidget a new UniqueKey when the recreate button is pressed. This will prevent Flutter from associating the old State with the new StatefulWidget.

It seems like you're mostly doing this out of curiosity rather than a genuine use case. The shopping card example you've described probably doesn't need to use initState and dispose at all and you should just use a StatelessWidget.

Tags:

Flutter