I am new in Flutter development. I’m been using GoRouter for the navigation between pages. I’m encountering an issue where the system brightness is out of the user’s control after it has been manipulated by the program.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:example/globals.dart';
import 'package:example/service/info_service.dart';
import 'package:screen_brightness/screen_brightness.dart';
class QrDisplay extends StatefulWidget {
const QrDisplay({Key? key}) : super(key: key);
@override
_QrDisplayState createState() => _QrDisplayState();
}
class _QrDisplayState extends State<QrDisplay> with WidgetsBindingObserver {
Globals? _globals;
bool _brightnessSet = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_setInitialBrightness();
}
Future<void> _setInitialBrightness() async {
_globals = Provider.of<Globals>(context, listen: false);
_globals?.previousBrightness = await ScreenBrightness().current;
await ScreenBrightness().setScreenBrightness(1.0);
setState(() {
_brightnessSet = true;
});
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_restoreBrightness();
super.dispose();
}
Future<void> _restoreBrightness() async {
if (_globals != null) {
await InfoService().restoreBrightnessToInit(_globals!.previousBrightness);
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive || state == AppLifecycleState.paused) {
_restoreBrightness();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 80),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_brightnessSet)
Image.asset(
'lib/assets/google_qr.png',
fit: BoxFit.cover,
)
else
CircularProgressIndicator(),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
try {
await _restoreBrightness();
if (mounted) {
GoRouter.of(context).pop();
}
} catch (e) {
print('Error restoring brightness: $e');
}
},
child: const Icon(Icons.close),
),
);
}
}
Once the QrDisplay page is loaded the system will force the screen brightness to it max and then restore to the previous brightness when it is popped. However after this, if the user wants to adjust the screen brightness in the app, the screen brightness would not change.