DEV Community

friendship
friendship

Posted on

FlutterFlow: Handling App Lifecycle to Run Actions on Foreground Transition

In FlutterFlow, pages do not provide a built-in Foreground Listener event.

Problem: Logs entered through the custom Log0ne keyboard need to be saved into the app’s internal data. However, since a keyboard extension cannot directly access the app’s data, we used UserDefaults to share the entered logs between the keyboard extension and the app. When the user launches or switches back to the Log0ne app, the logs from the keyboard extension are saved into the app’s data.

Solution

  • Create a custom widget called ForegroundListener. The widget takes an action as a parameter, which will be executed when the app returns to the foreground.
class ForegroundListener extends StatefulWidget {
  const ForegroundListener({
    super.key,
    this.width,
    this.height,
    this.onForeground,
  });

  final double? width;
  final double? height;
  final Future Function()? onForeground;

  @override
  State<ForegroundListener> createState() => _ForegroundListenerState();
}

class _ForegroundListenerState extends State<ForegroundListener>
    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) {
    if (state == AppLifecycleState.resumed) {
      widget.onForeground?.call();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

  • Place the custom widget on any page where you want to detect foreground transitions and run an action. In the property panel, set its size to 0 so it remains invisible, and pass the desired action as a parameter to be executed when the app returns to the foreground.

This way, logs entered through Log0ne’s custom keyboard extension can now be properly processed within the app.

Top comments (0)