简体   繁体   English

在Flutter中按下Enter键时,请始终保持软键盘处于打开状态

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

Is there a Flutter compatible way to always keep the keyboard open in the app and focused on a field? 是否有Flutter兼容的方法来始终保持应用程序中的键盘打开并专注于某个领域?

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". 我对这个Android问题有相同的要求:“我需要键盘始终可见,并专注于屏幕上唯一的Edit Text [Flutter TextField ]”。

In Android you could do this : 在Android中,你可以做这个

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;
    }
  }

});

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. 在TextField上设置autofocus = true可以在加载页面时获得焦点,并使用FocusNode和FocusScope始终将TextField设置为焦点。

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. 我不确定这对您有多重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM