首页 > 解决方案 > 如何获取 Flutter AlertDialog 动作以监视键盘事件(输入键)?

问题描述

有没有办法让颤动中的“输入”键键盘事件默认为我的 AlertDialog 上的一个操作按钮?注意我指的是在有物理键盘的情况下使用 web 的颤振。例如我有这个对话框:

  Future<void> _confirmDelete(int index) async {
    var fp = SessionInfo.of(context).myFloorplans.entries.toList()[index].value;
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Confirm Delete?'),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8.0))),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text("Please confirm deleting ${fp.name}"),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
              child: Text('Delete'),
              onPressed: () {
                _deleteFloorplan(index);
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

有没有办法默认键盘上的“输入”键就像他们点击删除一样?也许还不是最安全的 UI 体验,但主要只是要求了解这里的基础。

谢谢,贾斯汀

标签: flutterdartkeyboard

解决方案


您唯一需要做的就是将 AlertDialog 包装在 RawKeyboardListener 中。检查这个例子:

RawKeyboardListener(
// its better to initialize and dispose of the focus node only for this alert dialog 
  focusNode: FocusNode(),
  autofocus: true,
  onKey: (v) {
    if (v.logicalKey == LogicalKeyboardKey.enter) {
      _deleteFloorplan(index);
      Navigator.pop(context);
    }
  },
  child: your alert dialog ...

推荐阅读