显示键盘后如何拦截颤振后退按钮

时间:2019-08-30 13:06:46

标签: flutter keyboard back-button

我想在颤振中拦截软键盘的后退按钮。因此,当我想通过按后退按钮关闭键盘时,我希望调用其他功能。 我该怎么办?

键盘后退按钮

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用keyboard_visibility软件包来实现此目的。

工作示例

关闭键盘后,以下代码将显示SnackBar

import 'package:flutter/material.dart';
import 'package:keyboard_visibility/keyboard_visibility.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GlobalKey<ScaffoldState> _key;

  @override
  void initState() {
    super.initState();
    _key = GlobalKey<ScaffoldState>();
    KeyboardVisibilityNotification().addNewListener(
      onHide: () {
        _key.currentState.showSnackBar(
          SnackBar(
            content: Text("Keyboard closed"),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        key: _key,
        body: Center(
          child: TextField(),
        ),
      ),
    );
  }
}

enter image description here