7

I need to focus on a TextField but without showing the keyboard. The keyboard needs to be shown only if the user taps on the TextField.

I tried 2 ways.

First attempt:

This way the keyboard shows and it's hidden after screen build which is not nice to see.

Builder:

TextFormField(
    controller: barcodeStringController,
    focusNode: myFocusNode,
    autofocus: true,
    textAlign: TextAlign.right,
    textInputAction: TextInputAction.done,
    textCapitalization: TextCapitalization.characters,
    style: TextStyle(fontSize: 20),
    maxLines: null,
    onTap: () {
      SystemChannels.textInput.invokeMethod('TextInput.show');
    },
    //... Other event listeners to handle submit
),

And out of build():

void _onAfterBuild(BuildContext context) {
  SystemChannels.textInput.invokeMethod('TextInput.hide');
}

Second attempt:

This way the keyboard is hidden at a lower level and it's nicer to see. The problem is that onTap is never called so the keyboard never shows, neither onTap.

Builder:

GestureDetector(
    onTap: () {
        SystemChannels.textInput.invokeMethod('TextInput.show');
    },
    child: TapOnlyFocusTextField(
        controller: barcodeStringController,
        focusNode: myFocusNode, //this is a TapOnlyFocusTextFieldFocusNode
        textAlign: TextAlign.right,
        textInputAction: TextInputAction.done,
        textCapitalization: TextCapitalization.characters,
        style: TextStyle(fontSize: 20),
        cursorColor: Colors.black,
        //... Other event listeners to handle submit
    ),
),

TapOnlyFocusTextField Class:

class TapOnlyFocusTextField extends EditableText {
  TapOnlyFocusTextField({
    @required TextEditingController controller,
    @required TextStyle style,
    @required Color cursorColor,
    bool autofocus = false,
    Color selectionColor,
    FocusNode focusNode,
    TextAlign textAlign,
    TextInputAction textInputAction,
    TextCapitalization textCapitalization,
    onSubmitted,
    onChanged,
  }) : super(
          controller: controller,
          focusNode: focusNode,
          style: style,
          cursorColor: cursorColor,
          autofocus: autofocus,
          selectionColor: selectionColor,
          textAlign: textAlign,
          textInputAction: textInputAction,
          textCapitalization: textCapitalization,
          maxLines: null,
          onSubmitted: onSubmitted,
          backgroundCursorColor: Colors.black,
          onChanged: onChanged,
        );

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

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

TapOnlyFocusTextFieldFocusNode Class:

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

I know that there's already an open issue in Flutter Github about this but I need to find a solution: https://github.com/flutter/flutter/issues/16863

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
Davide Bicego
  • 562
  • 2
  • 6
  • 24
  • Are you sure the `GestureDetector` `onTap` is never called (have you added a print statement e.g.)? Tap events are passed down the tree, so the `GestureDetector` should consume it first. I might know a solution, but I am confused by this. Also, have you tested other `GestureDetector` callbacks? It might not be your desired behavior, but it can show useful insights if e.g. a long press on the text field triggers the gesture detector long press. – creativecreatorormaybenot Nov 27 '19 at 15:55
  • @creativecreatorormaybenot Yeah, neither onTap or onLongPress are being called – Davide Bicego Nov 27 '19 at 16:05
  • The problem in the second attempt is GestureDetector onTap not being called. I tried creating a button to show the keyboard and it works ok. – Davide Bicego Nov 27 '19 at 16:13
  • 1
    After further investigation I found out that onTap is called but not all the times (this is really strange) and I don't found out why. – Davide Bicego Nov 27 '19 at 16:51
  • Did you ever find a proper solution to your problem here? – Christo Carstens Jul 19 '21 at 01:27

3 Answers3

0

The text_input.dart has a method

    void show({bool ifShowKeyBoard = true}) {
      assert(attached);
      if (ifShowKeyBoard) {
        TextInput._instance._show();
      }
    }

I changed the method as this,It works

YuHao Zhu
  • 44
  • 3
0

As it is shown here: https://stackoverflow.com/a/60392327/4693979

But I prefer do this in initState:

  void initState() {
    super.initState();
    Future.delayed(
      Duration(),
      () => SystemChannels.textInput.invokeMethod('TextInput.hide'),
    );
  }

Do not forget to set autofocus to true.

K.Amanov
  • 1,278
  • 14
  • 23
0

How to focus on TextField without showing keyboard

You can acheive this buy creating your own UIViewRepresentable and changing the inputView of a UITextField.

The XTextField below will only show the keyboard when tapped after already holding focus. Customize this to your liking.

import SwiftUI
import UIKit

public struct XTextField: UIViewRepresentable {
    public init(
        _ placeholder: String,
        text: Binding<String>,
        onEditingChanged: ((Bool) -> Void)?,
        onCommit: (() -> Void)?,
        isFirstResponder: Binding<Bool>
    ) {
        self.placeholder = placeholder
        _text = text
        self.onEditingChanged = onEditingChanged
        self.onCommit = onCommit
        _isFirstResponder = isFirstResponder
    }

    public class Coordinator: NSObject, UITextFieldDelegate {
        init(_ xTextField: Binding<XTextField>) {
            _parent = xTextField
        }

        public func textFieldDidChangeSelection(_ textField: UITextField) {
            parent.text = textField.text ?? ""
        }

        public func textFieldDidBeginEditing(_: UITextField) {
            parent.isFirstResponder = true
            parent.onEditingChanged?(true)
        }

        public func textFieldDidEndEditing(_: UITextField) {
            parent.onEditingChanged?(false)
        }

        public func textFieldShouldReturn(_: UITextField) -> Bool {
            parent.isFirstResponder = false
            parent.onCommit?()
            return true
        }

        @Binding var parent: XTextField

        @objc func inputViewTapped(_ gesture: UITapGestureRecognizer) {
            if let textField = gesture.view as? UITextField {
                // Keyboard doesn't show unless tapped AFTER already being
                // firstResponder.
                if textField.isFirstResponder {
                    textField.inputView = nil // restores regular keyboard
                    textField.resignFirstResponder()
                } else {
                    textField.inputView = dummyInputView // suppresses keyboard
                }

                textField.becomeFirstResponder()
            }
        }
    }

    public func makeCoordinator() -> Coordinator {
        Coordinator(Binding(get: { self }, set: { _ in }))
    }

    public func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        textField.placeholder = placeholder
        textField.inputView = Self.dummyInputView // supress keyboard

        let tapGesture = UITapGestureRecognizer(
            target: context.coordinator,
            action: #selector(Coordinator.inputViewTapped(_:))
        )
        textField.addGestureRecognizer(tapGesture)

        return textField
    }

    public func updateUIView(_ uiView: UITextField, context _: Context) {
        uiView.text = text
        if isFirstResponder {
            Task { uiView.becomeFirstResponder() }
            return
        } else {
            Task { uiView.resignFirstResponder() }
        }
    }

    static let dummyInputView = UIView()

    @Binding var text: String
    @Binding var isFirstResponder: Bool

    private let placeholder: String
    private let onEditingChanged: ((Bool) -> Void)?
    private let onCommit: (() -> Void)?
}

Chris
  • 2,166
  • 1
  • 24
  • 37