Small details that build taste in Flutter.

curated by Kamran BekirovKamran Bekirov

Refresh the data when the user comes back

When the user comes back to the app after a while away, refresh the content for them, quietly. They shouldn't have to pull to refresh to see what's new.

Three rules make this feel good:

Not on every comeback. The user jumps to another app to reply to a message and comes back in 20 seconds. Nothing changed in 20 seconds, so don't fetch. In my BunPod app, podcast feeds are heavy RSS files, so I only refetch when the last fetch was more than 15 minutes ago.

Not when the app only loses focus. Pulling down the notification center, opening the app switcher, a permission dialog popping up. The user didn't go anywhere, so don't refetch (the widget I share below handles this).

Quietly. Don't reset the screen, don't show loading again, don't move things around. In BunPod, the only sign that a refresh is running is the logo in the app bar animating.

And one extra thing. When the refresh brings something new, don't let it just pop in, the list jumps and the user loses their place. Animate it in, so it's clear what's new and where. In BunPod, feed_arrival.dart slides each new episode into the list, one after another.

The listening part is one small widget:

class AppResumeListener extends StatefulWidget {
  const AppResumeListener({
    super.key,
    required this.onResume,
    required this.child,
  });
  
  final VoidCallback onResume;
  final Widget child;
  
  @override
  State<AppResumeListener> createState() => _AppResumeListenerState();
}
  
class _AppResumeListenerState extends State<AppResumeListener> {
  late final AppLifecycleListener _listener;
  bool _hidden = false;
  
  @override
  void initState() {
    super.initState();
  
    _listener = AppLifecycleListener(
      onHide: () {
        _hidden = true;
      },
      onShow: () {
        // skip if the app never really went to background
        if (!_hidden) return;
  
        _hidden = false;
        widget.onResume();
      },
    );
  }
  
  @override
  void dispose() {
    _listener.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

The _hidden flag is the whole trick. The notification center and the app switcher don't hide the app, they only take its focus. onHide fires when the user actually leaves, so onResume runs only on a real comeback.

Wrap your MaterialApp with it:

AppResumeListener(
  onResume: () {
    locator<FeedCubit>().refresh();
  },
  child: MaterialApp(
    // ...
  ),
)

All of this is from BunPod, which is open source: app_resume_listener.dart is the widget, app.dart is where it wraps the app, and feed_sync.dart has the 15 minute check.

Kamran Bekirov
Kamran Bekirov

Want this level of care in your Flutter apps?

Work With Me