【问题标题】:Flutter app crashes when back button is pressed按下后退按钮时 Flutter 应用程序崩溃
【发布时间】:2020-04-13 01:07:02
【问题描述】:

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

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

但是当按下返回按钮时我得到了非常奇怪的结果。

屏幕保持这样,当我再次单击返回按钮时,它停留在搜索页面。

【问题讨论】:

    标签: flutter flutter-navigation


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

    • 从根小部件中删除手动或自动返回按钮。

    另外,用WillPopScope 包裹root 小部件:

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

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

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

    关于屏幕显示的问题,

    如果 HomePage 是应用程序的父/根小部件,则在弹出 HomeWidget 时应该会导致黑屏。但看起来扭曲的屏幕视图是模拟器的一个错误。

    【讨论】:

    • 它仍然崩溃。
    • 更新了答案请看一下,如果您的问题得到解决,请告诉我。
    • 愚蠢的错误。我发现我已经为每个屏幕创建了 MaterialApp 小部件。我应该在问题中提供更多细节。移除多余的 MaterialApp 后,后退按钮开始正常工作。
    • 哦,好的。很高兴您找到了真正的原因并解决了它。
    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多