首页 > 解决方案 > 在导航回上一个屏幕之前无法隐藏/处置键盘

问题描述

我的目标只是从我所在的屏幕返回而不重建上一页上的小部件,我发现只要打开键盘,前一个屏幕中的小部件就会重建,但如果我通过点击后退按钮手动关闭键盘在我的手机上然后导航回小部件状态已恢复,所以我只想在返回上一页之前关闭键盘

页面示例

import 'package:flutter/material.dart';

class ScreenTwo extends StatefulWidget {
  final Function testFunction;
  final String title;

  const ScreenTwo({required this.testFunction, required this.title});
  @override
  _ScreenTwoState createState() => _ScreenTwoState();
}

class _ScreenTwoState extends State<ScreenTwo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.title,
        ),
      ),
      body: Column(
        children: [
          GestureDetector(
            child: Center(child: Text("Back")),
            onTap: () {
              Navigator.pop(context);
              widget.testFunction(false);
            },
          ),
          TextField(
            decoration: InputDecoration(
                border: OutlineInputBorder(), hintText: 'Enter a search term'),
          )
        ],
      ),
    );
  }
}

上一篇文章中商定的解决方案是FocusScopeNode,但它对我不起作用,我想 100% 确定键盘在我返回之前已关闭/处置。

 GestureDetector(
            child: Center(child: Text("Back")),
            onTap: () {
              FocusScopeNode currentFocus = FocusScope.of(context);
              if (!currentFocus.hasPrimaryFocus) {
                currentFocus.unfocus();
              }

              Navigator.pop(context);
              widget.testFunction(false);
            },
          ),

标签: flutterdart

解决方案


推荐阅读