How to intercept flutter back-button when keyboard is shown

微笑、不失礼 提交于 2020-06-15 18:38:44

问题


I want to intercept the back-button of the soft keyboard in flutter. So when I want to close the keyboard by pressing the back-button I want an additional function to be called. How can I do that?

Keyboard Back button


回答1:


you can use the keyboard_visibility package to achieve this.

Working Example

the following code displays a SnackBar once the keyboard is dismissed.

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



来源:https://stackoverflow.com/questions/57727350/how-to-intercept-flutter-back-button-when-keyboard-is-shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!