didChangePlatformBrightness method
override
Overrides the didChangePlatformBrightness method from the parent class.
This method gets information about the platform's brightness and updates the app if it ever changes. The changes are debounced with a timer to avoid them being too frequent.
Implementation
@override
void didChangePlatformBrightness() {
super.didChangePlatformBrightness();
// Get the binding instance
final binding = WidgetsFlutterBinding.ensureInitialized();
// Get the platform brightness from the PlatformDispatcher
// `_debounceBrightness` will then hold the new brightness
_debounceBrightness = binding.platformDispatcher.platformBrightness;
// If the current stored brightness value is different from the newly fetched value
if (_platformBrightness != _debounceBrightness) {
// If brightness has changed, cancel the existing timer and start a new one
// Cancel existing timer if any
_debounceTimer?.cancel();
// Start a new timer with `_debounceDuration` delay
_debounceTimer = Timer(_debounceDuration, () {
// Once timer fires, check if brightness is still different and not null
if (_debounceBrightness != null && _platformBrightness != _debounceBrightness) {
// If brightness value has indeed changed, update the state
setState(() {
// Set the new brightness value
_platformBrightness = _debounceBrightness!;
});
}
});
}
}