I want to secure content of my app when it's in the background. I wrote sample code that simply set flag if the app is active and widgets should be redrawn accordingly. However, it doesn't work every time on Android devices. Do you have an idea how to fix it? Is there a way to guarantee widgets reloading before minimising app?
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
var active = true;
@override
void initState() {
WidgetsBinding.instance?.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance?.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.resumed:
print('resumed');
setState(() {
active = true;
});
break;
case AppLifecycleState.inactive:
print('inactive');
setState(() {
active = false;
});
break;
case AppLifecycleState.paused:
print('paused');
setState(() {
active = false;
});
break;
case AppLifecycleState.detached:
print('detached');
break;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: MyApp._title,
home: Scaffold(
appBar: AppBar(),
body: Center(
child: Text(
active ? 'Revealed' : 'Secured',
style: const TextStyle(fontSize: 24),
),
),
),
);
}
}