0

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),
          ),
        ),
      ),
    );
  }
}
jakub
  • 3,576
  • 3
  • 29
  • 55
  • Flutter engine doesn't render widgets when the app goes in background, if you have any specific case where you required this, you can add it in your question. – Jitesh Mohite Oct 16 '21 at 09:45
  • I've written my specific case. It's securing content of my app. When it's going to background, I would like to hide the content. I don't need to render widgets specifically. Forcing rendering before going to background, or some other tricks that get the job done would work for me as well. – jakub Oct 16 '21 at 10:05
  • refer https://stackoverflow.com/questions/60006167/can-i-hide-flutter-app-contents-when-the-app-is-in-background – Jitesh Mohite Oct 16 '21 at 10:40

0 Answers0