Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always keep soft keyboard open when enter key is pressed in Flutter

Tags:

flutter

dart

Is there a Flutter compatible way to always keep the keyboard open in the app and focused on a field?

I have the same requirement from this Android question: "I need the keyboard to always be visible and focused on the only Edit Text [a Flutter TextField] on screen".

In Android you could do this:

EditText txtEdit = (EditText) findViewById(R.id.txtEdit);
txtEdit.setOnEditorActionListener(new OnEditorActionListener() {

  public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
      // your additional processing... 
      return true;
    } else {
      return false;
    }
  }

});
like image 531
S.D. Avatar asked Dec 24 '22 06:12

S.D.


1 Answers

Set the autofocus = true on your TextField to get the focus when the page is loaded and use FocusNode and FocusScope to always set the TextField focused.

Here is an example project:

import 'package:flutter/material.dart';

  void main() => runApp(MyApp());

  class MyApp extends StatefulWidget {
    @override
    _MyAppState createState() => _MyAppState();
  }

  class _MyAppState extends State<MyApp> {
    FocusNode _focusNode = FocusNode();

    @override
    void initState() {
      super.initState();

      _focusNode.addListener(() {
        if (!_focusNode.hasFocus) {
          FocusScope.of(context).requestFocus(_focusNode);
        }
      });
    }

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: Text('Focus Example')),
          body: Container(
            padding: EdgeInsets.all(20.0),
            child: Column(
              children: <Widget>[
                TextFormField(
                  focusNode: _focusNode,
                  decoration: InputDecoration(
                    labelText: 'Focued field'
                  ),
                  autofocus: true,
                ),
              ],
            ),
          ),
        ),
      );
    }
  }

Note: This approach will give a bumpy effect to the keyboard. I'm not sure how much does it matter to you.

like image 179
Javid Noutash Avatar answered Jan 25 '23 08:01

Javid Noutash