skip to Main Content

How to change that onSubmitted happens by pressing TAB:

Hello everyone, I’m a new developer in flutter and I have a question.
In the textField, how to make the onSubmitted function happen when TAB is pressed and not ENTER (which is the default)

I will rejoice in repentance!!

2

Answers


  1. Chosen as BEST ANSWER

    I meant that I want to catch an event of pressing the specific TAB key. So I ended up wrapping the widget in a KeyboardListener,Then every time I click Hunter in the TextField there will be a listening event. Here is the code:

    KeyboardListener(
                  focusNode: FocusNode(),
                  onKeyEvent: (value) {
                    if (value.logicalKey == LogicalKeyboardKey.tab) {
                      print("TAB key was pressed");
                    }
                  },
                  child: TextField(),
                ),
    

  2. You can use FocusNode to check if the textField is in focus. If it has lost the focus and the textField value is not empty, then it will run the code.

    Example:

    class TestPage extends StatefulWidget {
      const TestPage({super.key});
    
      @override
      State<TestPage> createState() => _TestPageState();
    }
    
    class _TestPageState extends State<TestPage> {
      final _focusNode = FocusNode();
    
      final _textEditingController = TextEditingController();
    
      void _onTab() {
        if (!_focusNode.hasFocus && _textEditingController.text.isNotEmpty) {
          print("Called OnSubmit");
        }
      }
    
      @override
      void initState() {
        super.initState();
        _focusNode.addListener(_onTab);
      }
    
      @override
      void dispose() {
        super.dispose();
        _focusNode.removeListener(_onTab);
        _focusNode.dispose();
        _textEditingController.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Center(
            child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              TextFormField(
                focusNode: _focusNode,
                style: const TextStyle(color: Colors.white),
                controller: _textEditingController,
                decoration: const InputDecoration(
                  hintText: "TEXT",
                ),
              ),
            ]),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search