You are currently viewing How To Detect App Focus in Flutter?

How To Detect App Focus in Flutter?

โ„น Introduction

How to detect app focus in Flutter and why? There are many reasons you might want to do that for example, You might want to focus on a certain widget, you might want to display any important alerts, you might want to refresh the screen or you might want to trigger a background task the possibilities are endless. But whatever your use case might be today I’ll show you how you can detect the focus gain or loss in your Flutter apps. So without any further delay lets get straight to it.

Getting Started

The best quality of the method I’m about to teach you is that there will be no dependencies for your project. Now lets start setting up our focus detection.

Setting up our Screen widget

  • All you have to do before you start is go to your stateful widget and ensure the state class implements WidgetsBindingObserver mixin. For example I created a widget called HomeScreen so I’ll go to _HomeScreenState and modify it like this
    class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver
  • Next We will override the initState method in _HomeScreenState and modify it like this
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }
  • Now we will override the dispose method like this.
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
  • Lastly we will override the didChangeAppLifecycleState method like this which is actually going to help us detect app focus in flutter app.
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text("App Gained Focus"),
      ));
    }
  }

Explanation

  • WidgetsBindingObserver mixin is used to enable our widget to access methods which enable us to add observers that will monitor our device for focus changes. This class serves more purposes too if you’d like to read more I suggest you read Flutter’s Documentation For WidgetsBindingObserver
  • In the next steps we initialize our widget and add it to the WidgetsBindingObserver’s observer list and then remove it from that same list when the widget using it is disposed off
  • didChangeAppLifecycleState function allows us to detect focus changes. The state parameter contains the current state of the app. There are many possible states you can use according to your needs. But to keep this tutorial concise I’ll only use “resumed” state because that is the one that shows our app gained focus. As you can see whenever the resumed state is detected the app will display a snackbar message.

๐Ÿ‘จโ€๐Ÿ’ป Complete Source Code

Here is the complete source code all assembled together.

import 'package:flutter/material.dart';

void main() {
  runApp(const MainApp());
}

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({
    super.key,
  });

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> 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) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
        content: Text("App Gained Focus"),
      ));
    }
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text('Codegitz Screen Focus Test'),
      ),
    );
  }
}

๐Ÿงช Testing The Result

As evident from the result above whenever our app is focused our observers detect the change. You can also use other states like hidden, inactive etc. Read more about them on Flutter’s API documentation.

๐Ÿ“ Conclusion

Today we learned how to detect screen focus changes in Flutter using WidgetsBindingObserver mixin. Then we overrode 3 functions which are initState, dispose and didChangeAppLifecycleState. Afterwards we witnessed how this approach works flawlessly and tracks all focus changes. That’s it for this post, if this post was helpful to you, you may like my other posts in the Flutter Archives. Thank you for reading.