Sometimes in your Flutter app, you need to know when the window size changes. This is important for making your app look good on different screen sizes or when the user rotates their phone.
How to catch size changes
The key to listening for these changes is a special helper called WidgetsBindingObserver
. It's like a spy that watches for things happening in the Flutter engine.
Setting up the listener
To start listening, your widget's State needs to with
the WidgetsBindingObserver
. This gives it the ability to receive updates.
In your initState
method, you need to tell the system you want to start listening. You do this by adding your widget's State as an observer to WidgetsBinding.instance
.
Reacting to changes
The WidgetsBindingObserver
requires you to implement a method called didChangeMetrics
. This method is automatically called whenever the screen size, device orientation, or other related things change.
Inside didChangeMetrics
, you can update your widget's state, for example, storing the new window size and rebuilding the UI to match.
Cleaning up
It's crucial to stop listening when your widget is removed. In the dispose
method, you must remove your widget's State as an observer. If you don't, your app might have problems or use too much memory.