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

时间:2018-07-04 07:53:37

标签: dart flutter

是否有Flutter兼容的方法来始终保持键盘在应用程序中打开并专注于某个领域?

对此Android question,我有相同的要求:“我需要键盘始终可见并集中在屏幕上唯一的“编辑文本[Flutter TextField]”上。”

在Android中,您可以执行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;
    }
  }

});

1 个答案:

答案 0 :(得分:3)

在页面加载时在TextField上设置autofocus = true以获得焦点,并使用FocusNode和FocusScope始终将TextField设置为焦点。

这是一个示例项目:

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,
                ),
              ],
            ),
          ),
        ),
      );
    }
  }

注意:这种方法会使键盘产生颠簸的效果。我不确定这对您有多重要。