我用TextFormField收集用户输入,当用户按下FloatingActionButton表示他们已经完成时,我想解散屏幕上的键盘。

如何让键盘自动消失?

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.send),
        onPressed: () {
          setState(() {
            // send message
            // dismiss on screen keyboard here
            _controller.clear();
          });
        },
      ),
      body: new Container(
        alignment: FractionalOffset.center,
        padding: new EdgeInsets.all(20.0),
        child: new TextFormField(
          controller: _controller,
          decoration: new InputDecoration(labelText: 'Example Text'),
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

void main() {
  runApp(new MyApp());
}

当前回答

在需要时调用此函数

  void hideKeyboard(BuildContext context) {
      FocusScopeNode currentFocus = FocusScope.of(context);
      if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
        FocusManager.instance.primaryFocus?.unfocus();
      }
    }

其他回答

FocusScope.of(上下文).unfocus ();是行不通的。

这段代码为我工作在颤振2.2.3和零安全。

WidgetsBinding.instance?.focusManager.primaryFocus?.unfocus()

来源:https://github.com/flutter/flutter/issues/20227 # issuecomment - 512860882

例如,把这段代码放在MyAppState中,当整个应用程序触摸外部时应用隐藏键盘。

return GestureDetector(
  onTap: () =>
      WidgetsBinding.instance?.focusManager.primaryFocus?.unfocus(),
  child: MaterialApp(
    title: 'Flutter Demo',
    theme: getTheme(),
    home: _body(),
  ),
);

这可能会简化情况。下面的代码只在键盘打开时才会工作

if(FocusScope.of(context).isFirstFocus) {
 FocusScope.of(context).requestFocus(new FocusNode());
}

下面的代码帮助我隐藏键盘

   void initState() {
   SystemChannels.textInput.invokeMethod('TextInput.hide');
   super.initState();
   }

如果你的键盘仍然不会关闭,不要忘记添加focusNode到TextField。上面的信息很有帮助,但是忘记添加focusNode让我有点困扰。这里有一个例子。

TextField(
          focusNode: FocusNode(),
          textController: _controller,
          autoFocus: false,
          textStyle: TextStyle(fontSize: 14),
          onFieldSubmitted: (text) {},
          onChanged: (text) {},
          hint: 'Enter the code',
          hintColor: CustomColors.mediumGray,
          suffixAsset: _voucherController.text.length == 7
              ? Assets.ic_approved_voucher
              : null,
          isIcon: false,
          isObscure: false,
          maxLength: 7,
        )



closeKeyboard(BuildContext context) {
    var currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus) {
      currentFocus.unfocus();
    }
  }

  @override
  Widget build(BuildContext context) {
    _keyboardVisible = MediaQuery.of(context).viewInsets.bottom != 0;
    size = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: () {
        closeKeyboard(context);
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        body: Container(
            width: double.maxFinite,
            height: double.maxFinite,
            child: _buildUI(vm)),
      ),
    );
  }

看起来不同的版本用不同的方法。我使用的是Flutter v1.17.1,下面的操作适合我。

onTap: () {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
       currentFocus.focusedChild.unfocus();
    }
}