Flutter How to alway hide keyboard when click on T

2020-07-17 04:54发布

问题:

I can't control keyboard show or hide, In my project I need to always hide keyboard but keep focused to display my custom keyboard(a widget).

Need Help!!!

This is I want

And this is my problem

回答1:

To hide keyboard and keep the cursor visible, set readOnly to true and showCursor to true.

TextFormField(
  showCursor: true,
  readOnly: true),

See flutter/issues/#16863



回答2:

Insert NoKeyboardEditableText instead your TextField

class NoKeyboardEditableText extends EditableText {

  NoKeyboardEditableText({
    @required TextEditingController controller,
    TextStyle style = const TextStyle(),
    Color cursorColor = Colors.black,
    bool autofocus = false,
    Color selectionColor
  }):super(
      controller: controller,
      focusNode: NoKeyboardEditableTextFocusNode(),
      style: style,
      cursorColor: cursorColor,
      autofocus: autofocus,
      selectionColor: selectionColor,
      backgroundCursorColor: Colors.black
  );

  @override
  EditableTextState createState() {
    return NoKeyboardEditableTextState();
  }

}

class NoKeyboardEditableTextState extends EditableTextState {

  @override
  Widget build(BuildContext context) {
    Widget widget = super.build(context);
    return Container(
      decoration: UnderlineTabIndicator(borderSide: BorderSide(color: Colors.blueGrey)),
      child: widget,
    );
  }

  @override
  void requestKeyboard() {
    super.requestKeyboard();
    //hide keyboard
    SystemChannels.textInput.invokeMethod('TextInput.hide');
  }
}

class NoKeyboardEditableTextFocusNode extends FocusNode {
  @override
  bool consumeKeyboardToken() {
    // prevents keyboard from showing on first focus
    return false;
  }
}


回答3:

You can use custom focusNode

This prevents keyboard appearing only on first tap:

TextField(focusNode: FirstDisabledFocusNode(),)

class FirstDisabledFocusNode extends FocusNode {
  @override
  bool consumeKeyboardToken() {
    return false;
  }
}

This prevents always:

TextField(focusNode: AlwaysDisabledFocusNode())

class AlwaysDisabledFocusNode extends FocusNode {
  @override
  bool get hasFocus => false;
}