How to detect when a TextField is selected in Flutter?

前端 未结 5 2014
猫巷女王i
猫巷女王i 2020-12-13 02:24

I have a Flutter TextField which gets covered by the soft keyboard when the field is selected. I need to scroll the field up and out of the way when the keyboard is displaye

相关标签:
5条回答
  • 2020-12-13 02:49

    Simply use onTap function of TextField.

    TextField(
      onTap: () {
        // Your code.
      },
    );
    
    0 讨论(0)
  • 2020-12-13 02:50

    The easiest and simplest solution is to add the onTap method on TextField.

    TextField(
      onTap: () {
        print('Editing stated $widget');
      },
    )
    
    0 讨论(0)
  • 2020-12-13 02:51

    To be notified about a focus event, you can avoid manually managing widget's state, by using the utility classes FocusScope, Focus.

    From the docs (https://api.flutter.dev/flutter/widgets/FocusNode-class.html):

    Please see the Focus and FocusScope widgets, which are utility widgets that manage their own FocusNodes and FocusScopeNodes, respectively. If they aren't appropriate, FocusNodes can be managed directly.

    Here is a simple example:

    FocusScope(
      child: Focus(
        onFocusChange: (focus) => print("focus: $focus"),
        child: TextField(
          decoration: const InputDecoration(labelText: 'City'),
        )
      )
    )
    
    0 讨论(0)
  • 2020-12-13 03:05

    I suppose you are looking for FocusNode.

    To listen to focus change, you can add a listner to the FocusNode and specify the focusNode to TextField.

    Example:

    class TextFieldFocus extends StatefulWidget {
      @override
      _TextFieldFocusState createState() => new _TextFieldFocusState();
    }
    
    class _TextFieldFocusState extends State<TextFieldFocus> {
      FocusNode _focus = new FocusNode();
    
      TextEditingController _controller = new TextEditingController();
    
      @override
      void initState() {
        super.initState();
        _focus.addListener(_onFocusChange);
      }
    
      void _onFocusChange(){
        debugPrint("Focus: "+_focus.hasFocus.toString());
      }
    
      @override
      Widget build(BuildContext context) {
        return new Container(
          color: Colors.white,
          child: new TextField(
            focusNode: _focus,
          ),
        );
      }
    }
    

    This gist represents how to ensure a focused node to be visible on the ui.

    Hope it helps!

    0 讨论(0)
  • 2020-12-13 03:11

    There is another way if your textfield needs to be disabled for some purpose like mine. for that case, you can wrap your textField with InkWell like this,

    InkWell(
      onTap: () {
        print('clicked');
      },
      child: TextField(
        enabled: false,
      ),
    );
    
    0 讨论(0)
提交回复
热议问题