How to Listen Focus Change In Flutter ??

· 3 min read
How to Listen Focus Change In Flutter
How to Listen Focus Change In Flutter

In Android, we can call setOnFocusChangeListener(), do something in onFocusChanged() method, but flutter does not provider onFocus() interface like onTap() in GestureDetector or onKey() in RawKeyboardListener. so in this article we will go through how to Listen Focus Change in flutter ??

How to Listen Focus Change In Flutter ??

Using FocusNode

Here is a fully correct answer. addListener shall be in initState(), not build() because that would result in adding a listener every time a widget is built and you most likely don’t want that.

import 'package:flutter/material.dart';

class SomeWidget extends StatefulWidget {
  @override
  _SomeWidgetState createState() => _SomeWidgetState();
}

class _SomeWidgetState extends State<SomeWidget> {
  final _focusNode = FocusNode();
    
  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      print("Has focus: ${_focusNode.hasFocus}");
    });
  }
    
  @override
  Widget build(BuildContext context) {
    return TextField(focusNode: _focusNode);
  }
    
  @override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }
}

So if you’re by any chance using the flutter hooks package, there is a dedicated useFocusNode hook.

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

class SomeWidget extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final focusNode = useFocusNode();
    useEffect(() {
      focusNode.addListener(() {
        print("Has focus: ${focusNode.hasFocus}");
      });
      return; // You need this return if you have missing_return lint
    }, [focusNode]);

    return TextField(focusNode: focusNode);
  }
}

In addition, you can use the Focus widget.

Focus(
  child: TextFormField(...),
  onFocusChange: (hasFocus) {
    if(hasFocus) {
      // do stuff
    }
  },
)

Conclusion:

We believe you have enjoyed this article and learned something new!!!

So in this article, we have been through how to listen to focus change in Flutter…

Also, Check RawKeyboardListener Widget.

Do not forget to drop your valuable suggestions/feedback. We would love to assist you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

2 comments

    1. Hey tom,

      Focus is a widget that has inbuilt focus listeners and focus management functionalities. While FocusNode is an API to handle focus on any widget manually.

      Hope that clears your doubt 🙂 Have a great one tom!!

Leave a Reply