skip to Main Content

I want to implement a global widget which handles the app state.
What i want to do is suppose i am on home screen of the application and now i put the app in background.

Now lets suppose if i re – opens the app and app comes in foreground and the time difference between app background and foreground is more than 30 minutes the i want to refresh home screen.

This should happens if i implemented that global widget in any other screen , lets say cart screen.

Please help me with the code in flutter

2

Answers


  1. Can you try checking AppLifecycleState.resumed in didChangeAppLifecycleState() ?

    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
      if (state == AppLifecycleState.resumed) {
        _refreshData();
      }
    }
    
    Login or Signup to reply.
    • Use WidgetsBindingObserver to notify when app state change (go background, foreground…)
    • Write data date time (to local storage) when app go to background
    • Get this data when app is back to foreground then compare
    class _HomeScreenState extends State<HomeScreenState> with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this); // <--------
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this); // <--------
        super.dispose();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        // check when app go foreground
        if (state == AppLifecycleState.resumed) {
          final lastTimeGoBackground = getLastTimeGoBackgroundFromLocalStorage();
          final now = DateTime.now();
          if (now.isAfter(lastTimeGoBackground) && now.difference(lastTimeGoBackground).inMinutes >= 30) {
            // do your stuff here
          }
        }
    
        // write data date time when app go background
        if (state == AppLifecycleState.paused) {
          final now = DateTime.now();
          setLastTimeGoBackgroundFromLocalStorage(now);
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search