我用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());
}

当前回答

你可以用"GestureDetector"来包装你的小部件,然后将"FocusScope.of(context).unfocus()"赋值给它的onTap函数

GestureDetector(
 onTap: () => FocusScope.of(context).unfocus(),
 child: child,
);

其他回答

======解散键盘后,点击TextField =======

 @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),  //this will dismiss keyboard
      child: Scaffold(
        body: SafeArea(
               .........

======滚动屏幕时关闭键盘=======

ListView(
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, //this will dismiss
            children: [
               ..........

SingleChildScrollView小部件也有这个属性。

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

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

注意:这个答案已经过时了。有关Flutter的新版本,请参阅答案。

你可以通过把TextFormField的焦点拿走,并把它给一个未使用的FocusNode来解散键盘:

FocusScope.of(context).requestFocus(FocusNode());
GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child:Container(
    alignment: FractionalOffset.center,
    padding: new EdgeInsets.all(20.0),
    child: new TextFormField(
      controller: _controller,
      decoration: new InputDecoration(labelText: 'Example Text'),
    ),
  ), })

试试这个动作

_dismissKeyboard(BuildContext context) {
   FocusScope.of(context).requestFocus(new FocusNode());
}

@override
Widget build(BuildContext context) {

return new GestureDetector(
    onTap: () {
    this._dismissKeyboard(context);
    },
    child: new Container(
    color: Colors.white,
    child: new Column(
        children: <Widget>[/*...*/],
    ),
    ),
 );
}