按下后退按钮时Flutter应用程序崩溃

时间:2019-12-20 14:09:21

标签: flutter flutter-navigation

我的应用程序的主页上有一个搜索栏。点击搜索栏后,用户将被重定向到搜索页面,如下所示:

class _HomeAppBarState extends State<HomeAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        backgroundColor: Colors.white,

        leading: IconButton(
            icon: Icon(Icons.account_circle, color: Colors.black) , onPressed: () => Scaffold.of(context).openDrawer()
        ),

        title: TextField(
          onTap: () {Navigator.push(context, MaterialPageRoute(builder: (context) => Search()));},
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search, color: Colors.black),
            hintText: "Search...",
          ),
        )
    );
  }
}

在搜索页面中。应用栏上有一个后退按钮,然后按下了后退按钮,我希望用户被带回主页。我尝试通过使用Navigator.pop进行以下操作:


class _SearchAppBarState extends State<SearchAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
        backgroundColor: Colors.white,

        leading: IconButton(
            icon: Icon(Icons.arrow_back, color: Colors.black) , onPressed: () => Navigator.pop(context)
        ),

        title: TextField(
          autofocus: true,
          //onChanged: Do Stuff here.
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search, color: Colors.black),
            hintText: "Search App Bar...",
          ),
        )
    );
  }
}

但是当按下后退按钮时,我得到了非常奇怪的结果。

When the back button pressed at search page.

屏幕保持这样,当我再次单击“后退”按钮时,它停留在搜索页面上。

1 个答案:

答案 0 :(得分:1)

  • 仅在搜索栏小部件上尝试使用automaticallyImplyLeading: true, ,而不是提供后退按钮并手动处理导航堆栈。

  • 从根窗口小部件中删除手动或自动“后退按钮”。

另外,用WillPopScoperoot小部件包裹起来:

build(BuildContext context) {
  return WillPopScope(
    onWillPop: () async => false,
     child: //you root widget,
    ); 
}

WillPopScope小部件将忽略任何向后按下事件,以弹出“ root”小部件,因此不会出现像您遇到的问题。

有关WillPopScope的更多详细信息,请访问本文: https://codingwithjoe.com/flutter-navigation-how-to-prevent-navigation/

关于屏幕视图的问题,

如果HomePage是应用程序的父/根窗口小部件,则在弹出HomeWidget时,它将导致黑屏。但是似乎扭曲的屏幕视图是模拟器的错误。

相关问题