Skip to content

Render widgets based on AppLifeCycleState is not working (build method is never called for inactive state) #33236

Closed

Description

@pravinarr

I have the following code which will replace the child with a container when the app goes to inactive or paused state.


import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        body: SecureScreen(
          child: Container(
            color: Colors.red,
          ),
        ),
      ),
    );
  }
}

class SecureScreen extends StatefulWidget {
  final Widget child;
  SecureScreen({@required this.child});

  @override
  SecureScreenState createState() => SecureScreenState();
}

class SecureScreenState extends State<SecureScreen>
    with WidgetsBindingObserver {
  AppLifecycleState _notification;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print(state.toString());
    setState(() {
      _notification = state;
    });
  }

  @override
  Widget build(BuildContext context) {
    return (_notification == AppLifecycleState.paused ||
            _notification == AppLifecycleState.inactive)
        ? Container(
            color: Colors.greenAccent,
          )
        : widget.child;
  }
}


So when I double click the home button in IOS to view all the open applications, it is triggering
"inactive" state but it is not calling the build() method to render container with greenAccent color.

I have attached the screenshot for you reference.

Does this needs additional code to achieve the result ?
image

Activity

  1. changed the title [-]Render widgets based on AppLifeCycleState, Hide the page when viewing list of running apps[/-] [+]Render widgets based on AppLifeCycleState is not working (build method is never called for inactive state)[/+] on May 23, 2019
  2. pravinarr commented on Jun 18, 2019

    @pravinarr
    Author

    Related #27344 #28936

  3. added
    engineflutter/engine related. See also e: labels.
    frameworkflutter/packages/flutter repository. See also f: labels.
    platform-iosiOS applications specifically
    on Jun 19, 2019
  4. dnfield commented on Jun 19, 2019

    @dnfield
    Contributor

    I suspect what we want here is something in viewWillDisappear getting pumped down to the framework somehow. I don't think we can reliably expect anything to execute in a paused/inactive state for drawing on the screen.

  5. dnfield commented on Jun 19, 2019

    @dnfield
    Contributor

    Per input from @matthew-carroll marking this as critical. Customer(s) who want to hide what's on the screen before going to background need this.

  6. matthew-carroll commented on Jun 19, 2019

    @matthew-carroll
    Contributor

    Triage note: This issue prevents security conscious apps from clearing sensitive UI from apps that are moved to background.

  7. added this to the milestone on Jun 19, 2019
  8. dnfield commented on Jun 19, 2019

    @dnfield
    Contributor

    I'm not sure that there's goin got be a great way to do this in Dart - particularly in a way that would guarantee that a message arrived in Dart land in time for Flutter to render a new frame with the desired content.

    However, you can do this pretty trivially in a Flutter app. On iOS, following https://developer.apple.com/library/archive/qa/qa1838/_index.html, I changed up AppDelegate.m in a sample project to be like this:

    #include "AppDelegate.h"
    #include "GeneratedPluginRegistrant.h"
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      [GeneratedPluginRegistrant registerWithRegistry:self];
      // Override point for customization after application launch.
      return [super application:application didFinishLaunchingWithOptions:launchOptions];
    }
    
    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        // Your application can present a full screen modal view controller to
        // cover its contents when it moves into the background. If your
        // application requires a password unlock when it retuns to the
        // foreground, present your lock screen or authentication view controller here.
    
        UIViewController *blankViewController = [UIViewController new];
        blankViewController.view.backgroundColor = [UIColor blackColor];
    
        // Pass NO for the animated parameter. Any animation will not complete
        // before the snapshot is taken.
        [self.window.rootViewController presentViewController:blankViewController animated:NO completion:NULL];
    }
    
    - (void)applicationWillEnterForeground:(UIApplication *)application
    {
        // This should be omitted if your application presented a lock screen
        // in -applicationDidEnterBackground:
        [self.window.rootViewController dismissViewControllerAnimated:NO completion:NO];
    }
    
    @end

    And now I get a black screen in the switcher.

  9. pravinarr commented on Jun 20, 2019

    @pravinarr
    Author

    @dnfield Thank you for providing workaround for this issue. It worked perfectly. Can you provide some guidance to achieve the same on android?

  10. dnfield commented on Jun 20, 2019

    @dnfield
    Contributor

    You can add getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); to onCreate of MainActivity.java, which will also end up preventing screen shots from working. If you want it only to work when the app gets backgrounded, you could instead do something like

        @Override
        public void onResume() {
            super.onResume();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }
    
        @Override
        public void onPause() {
            super.onPause();
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }

    Although I'm not 100% sure this would end up covering something like an embedded platform view (e.g. a webview in your flutter app).

  11. dnfield commented on Jun 20, 2019

    @dnfield
    Contributor

    Based on the work arounds available for this, I'm going to remove the critical label. Please let me know (or feel free to re-add it if you're able) if this needs more attention again.

    In case it's not already clear, I think it's unlikely that we'll be able to do a whole lot here on the framework side for this, but perhaps there's some good way to turn this into a plugin of some sort.

  12. 22 remaining items

  13. gabdsg commented on May 13, 2020

    @gabdsg

    Any updates?

  14. added
    P3Issues that are less important to the Flutter project
    on May 29, 2020
  15. duck-dev-go commented on Jul 10, 2020

    @duck-dev-go

    Any updates?

  16. removed this from the milestone on Aug 17, 2020
  17. muarachmann commented on Sep 28, 2020

    @muarachmann

    The Flutter Application doesn't override methods like onResume, onPause, is there anyway to by pass this? Also tried getting getCurrentActivity().onPause(....) but not working says its protected. I will appreciate any help thanks

  18. muarachmann commented on Sep 28, 2020

    @muarachmann

    The Flutter Application doesn't override methods like onResume, onPause, is there anyway to by pass this? Also tried getting getCurrentActivity().onPause(....) but not working says its protected. I will appreciate any help thanks

    Used Application.ActivityLifecycleCallbacks and registerActivityLifecycleCallbacks(listener) then I could access the onActivityResumed() and onActivityPaused()

  19. Jethro87 commented on Oct 21, 2020

    @Jethro87

    @audente Would you mind posting your Kotlin code from #33236 (comment)? Your swift code was super helpful, thanks 👍

  20. Jethro87 commented on Oct 21, 2020

    @Jethro87

    Managed to get it working. Reference for those that come across this issue:

    import androidx.annotation.NonNull;
    import io.flutter.embedding.android.FlutterFragmentActivity;
    import io.flutter.embedding.engine.FlutterEngine;
    import io.flutter.plugins.GeneratedPluginRegistrant;
    import android.view.WindowManager;
    import android.os.Bundle;
    
    class MainActivity: FlutterFragmentActivity() {
        override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
            GeneratedPluginRegistrant.registerWith(flutterEngine);
        }
        override fun onCreate(savedInstanceState : Bundle?) {
            super.onCreate(savedInstanceState);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);    
        }
    }
    

    Note that this is using FlutterFragmentActivity instead of FlutterActivity. Cheers.

  21. AdeolaKOD commented on Nov 15, 2020

    @AdeolaKOD

    Managed to get it working. Reference for those that come across this issue:

    import androidx.annotation.NonNull;
    import io.flutter.embedding.android.FlutterFragmentActivity;
    import io.flutter.embedding.engine.FlutterEngine;
    import io.flutter.plugins.GeneratedPluginRegistrant;
    import android.view.WindowManager;
    import android.os.Bundle;
    
    class MainActivity: FlutterFragmentActivity() {
        override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
            GeneratedPluginRegistrant.registerWith(flutterEngine);
        }
        override fun onCreate(savedInstanceState : Bundle?) {
            super.onCreate(savedInstanceState);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);    
        }
    }
    

    Note that this is using FlutterFragmentActivity instead of FlutterActivity. Cheers.

    Thanks for this. I was able to get it working.

    Just to clarify, on IOS the result of the swift code from @audente and @dnfield , will only be able to show us a blank screen when switching apps ?

  22. gaaclarke commented on Mar 29, 2021

    @gaaclarke
    Member
  23. fribeau commented on Apr 10, 2021

    @fribeau

    It seems that the same issue is also happening on Android.
    I just copied-pasted the same exact code shown at the beginning of this issue (minus some question marks in order to work with null safety) and I have the same unwanted behavior: the background stays always red no matter the state.

    Does the fixed made 12 days ago only works for iOS or should I try another approche than WidgetsBindingObserver to reach the same goal ?

    This is the output of my flutter doctor (I work with a Pixel 5):

    Doctor summary (to see all details, run flutter doctor -v):
    [✓] Flutter (Channel master, 2.1.0-13.0.pre.574, on Linux, locale fr_FR.UTF-8)
    [✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
    [✓] Chrome - develop for the web
    [✓] Linux toolchain - develop for Linux desktop
    [✓] Android Studio (version 4.1)
    [✓] Android Studio
    [✓] IntelliJ IDEA Community Edition (version 2019.3)
    [✓] VS Code (version 1.55.0)
    [✓] Connected device (3 available)
    
    • No issues found!
  24. gaaclarke commented on Apr 12, 2021

    @gaaclarke
    Member

    @fribeau can you file another issue for android, please? If the steps are the same, just copy and paste them and link this issue.

    The fix will only work for iOS, there isn't a cross platform solution since it's tightly tied to the embedder.

  25. github-actions commented on Aug 3, 2021

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  26. locked as resolved and limited conversation to collaborators on Aug 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: new featureNothing broken; request for a new capabilityengineflutter/engine related. See also e: labels.frameworkflutter/packages/flutter repository. See also f: labels.platform-iosiOS applications specifically

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions