How to listen focus change in flutter?

后端 未结 3 1211
轻奢々
轻奢々 2021-02-02 05:50

In Android, we can call setOnFocusChangeListener(), do something in onFocusChanged() method, but flutter does not provider onFocus() inter

3条回答
  •  难免孤独
    2021-02-02 06:27

    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 {
      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();
      }
    }
    

    Using flutter_hooks package

    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);
      }
    }
    

提交回复
热议问题