如何使用 FLUTTER go_router 弹出上下文?

8
如何使用flutter的go_router返回上一个屏幕?如何弹出上下文?
目前,我只是将新屏幕添加到堆栈中,无论是要返回还是前进。
 onTap: (() => context.go("/secondPage"))

我使用了context.pop(),但它会抛出错误,显示-
_AssertionError ('package:go_router/src/matching.dart': Failed assertion: line 102 pos 9: '_matches.isNotEmpty': You have popped the last page off of the stack, there are no pages left to show)

2个回答

13
如果你的页面通过"go_router"呈现,则可以使用"context.pop()"。但是如果你正在使用showModalBottomSheet或Dialog类,则应继续使用Navigator.pop(context)。

4
好的,那个可行。我必须使用context.push("/secondPage")才能使用context.pop()。谢谢。 - Srasti Verma

6

您可以使用context.pop()进行弹出。

但是,要弹出某些内容,它必须在路由堆栈中。

所以,实际问题是如何将路由放入路由器堆栈中。 Go_router有两种方法gopush,都会带您到指定的下一个屏幕。

但是,push将总是向堆栈添加(推送)新路由,而go仅在被指定为上一个屏幕的子路由时才添加新路由。否则,它将用新路由替换以前的路由。

因此,使用给定的示例:

要么使用push

 onTap: (() => context.push("/secondPage"));

或将secondPage指定为firstPage的子路由,然后使用go

GoRoute(
    path: "/firstPage",
    builder: (context, state) => const FirstPage(),
    routes: [
      GoRoute(
        path: "secondPage",
        builder: (context, state) => const SecondPage(),
      ),

    ],
  ),

...

   onTap: (() => context.go("/secondPage"));

这是我学到以上所有内容的文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接