一尘不染

如何关闭屏幕键盘?

flutter

我正在使用a收集用户输入,TextFormField并且当用户按a 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());
}

阅读 301

收藏
2020-08-13

共1个答案

一尘不染

注意:
此答案已过时。

您可以通过移开键盘的焦点TextFormField并将其分配给未使用的键盘来关闭键盘FocusNode

FocusScope.of(context).requestFocus(FocusNode());
2020-08-13