How can I refresh the page when the user comes back to the app (from background)?

Viewed 1187

Right now the only way my app can refresh (it's a news app so it needs to constantly refresh) is two ways: 1) Refresh by scrolling up or 2) Restart the app after killing it from background.

I want to make it so that when a user just comes back to the app (say I'm using my app, then I go to WeChat to send a text, then I come back), the app is refreshed.

This is the refresh scroll code.

final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
new GlobalKey<RefreshIndicatorState>();

Then it calls this function:

Future<void> _refresh() async {
  print("Refreshed");
  Navigator.pushReplacement(
    context,
    MaterialPageRoute(
      builder: (context) => MyHomePage(),
    ),
  ).then((value) => null);
}

What should I do to achieve what I need?

Is there a way to check if someone has "returned" to my app? Then I can just call the function.

2 Answers

You need to subscribe to the application life cycle. In Flutter it's not build in the same was it is natively. However, there is a good article I stumbled across a last year, trying to accomplish the same thing:

https://medium.com/pharos-production/flutter-app-lifecycle-4b0ab4a4211a

The gist of the implementation looks like this:

class MyHomePage extends StatefulWidget {
  @override _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {
  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

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

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('state = $state');
  }

  @override
  Widget build(BuildContext context) {
    return YourWidget();
  }
}

A better solution is to give the child widget of your FutureBuilder or StreamBulder a random unique key. This forces the underlying widget to redraw (and trigger the future or stream) when you come back from the background.

key: UniqueKey(), 

Example:

    return FutureBuilder<PriceData>(
        future: DbService.getPriceData(),
        builder: (context, priceData) {
          if (priceData.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          return AnimatedAppear(
            key: UniqueKey(), <---- here!
Related