0

I have two stateful widgets: Widget1 and Widget2. Both defines the didChangeAppLifecycleState method. When there is a change in the lifecycle of Widget1, it's corresponding didChangeAppLifecycleState method is being called, but that for Widget2 is also being called.

Is that the normal behavior, is there a way to avoid this so that if for example, the app is put in the background while Widget1 is being shown, only the didChangeAppLifecycleState in Widget1 is called?

Noor
  • 19,638
  • 38
  • 136
  • 254

2 Answers2

3

The didChangeAppLifecycleState is triggered according to the life cycle of your application. Every didChangeAppLifecycleState registered using WidgetsBindingObserver will be called when the app goes to the background or resumes etc.

If you want to execute a general logic only once when the application's life cycle changes, implement it in your home widget's didChangeAppLifecycleState.

You can use other widget's didChangeAppLifecycleState methods to perform actions specific to that widget. A common example is to dispose / recreate a controller when the app is backgrounded / resumed.

Peter Koltai
  • 8,296
  • 2
  • 10
  • 20
0

didChangeAppLifecycleState is a method that is part of the WidgetsBindingObserver class, which allows widgets to register as observers of the application's lifecycle events. This method is called whenever the state of the application's lifecycle changes, such as when the app is brought to the foreground or background.

If you are seeing didChangeAppLifecycleState being called twice in two different views, it is likely because both of those views are registered as observers of the application's lifecycle events. When the state of the application's lifecycle changes, all registered observers will receive the event.

To avoid duplicate calls to didChangeAppLifecycleState, you can ensure that only one view is registered as an observer of the application's lifecycle events. You can do this by making sure that only one widget in your app is extending WidgetsBindingObserver and registering itself as an observer.