如何使用 Getx 和自动路由设置导航器?

Bio*_*osx 5 flutter flutter-getx

问题: 我在使用 GetX 和 AutoRoute 设置导航时遇到问题。

代码设置: 根据 GetX 文档,如果您想使用 GetX 导航,则必须将 MaterialApp() 替换为 GetMaterialApp()。您还设置了路线。

void main() {
  runApp(
    GetMaterialApp(
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => MyHomePage()),
        GetPage(name: '/second', page: () => Second()),
        GetPage(
          name: '/third',
          page: () => Third(),
          transition: Transition.zoom  
        ),
      ],
    )
  );
}
Run Code Online (Sandbox Code Playgroud)

AutoRoute示例使用MaterialApp.router()来设置routerDelegate和routeInformationParser。

   final _appRouter = AppRouter()  
   ...  
  Widget build(BuildContext context){  
      return MaterialApp.router(  
             routerDelegate: _appRouter.delegate(...initialConfig),  
             routeInformationParser: _appRouter.defaultRouteParser(),  
         ),  
  } 
Run Code Online (Sandbox Code Playgroud)

以下是我根据 Getx 和 AutoRoute 设置导航的方法:

void main() {
 configureDependencies();
 runApp(Portfolio());
}

class Portfolio extends StatelessWidget {
  final _appRouter = AppRouter.Router();
  @override
  Widget build(BuildContext context) {
  return GetMaterialApp.router(
      routerDelegate: _appRouter.delegate(),
      routeInformationParser: _appRouter.defaultRouteParser(),
      builder: (context, extendedNav) => Theme(
          data: ComplexReduxTheme.complexReduxLightTheme,
          child: extendedNav ?? Container(color: Colors.red),
         ),
      );
    }
  } 
Run Code Online (Sandbox Code Playgroud)

我正在使用 GetMaterialApp.router 它返回 GetMaterialApp。尽管如此,我还是收到错误“您正在尝试在没有 GetMaterialApp 或 Get.key 的情况下使用无上下文导航。”。我尝试设置导航键并设置 Get.testMode = true 但当我尝试导航到另一个屏幕时没有任何反应(没有错误)。

期望的结果: 我应该能够通过 Get.toNamed() 导航到所需的屏幕。

当前结果: 当尝试使用 Get.toNamed() 导航到另一个屏幕时,我从 GetX 收到以下错误:“您正在尝试在没有 GetMaterialApp 或 Get.key 的情况下使用无上下文导航。如果您正在测试您的应用程序,则可以使用:[Get.testMode = true],或者如果您在物理设备或模拟器上运行应用程序,则必须将 [MaterialApp] 替换为 [GetMaterialApp]。”

自动路线版本: 2.2.0

获取版本: 4.1.4

Tam*_*mma 0

你不需要外部路由插件,GetX 已经为你做到了这一点,如果你想导航,只需使用Get.toNamed("/some-page")它就会显示你想要的页面。嵌套路由也是如此。

例如

GetPage(
  name: '/third',
  page: () => Third(),
  transition: Transition.zoom,
  children: [
    GetPage(
      name: '/child-of-third',
      page: () => ChildOfThird(),
    ),
   ],
),

// You access it like this
Get.toNamed("/third");

// And this one, for the nested page
Get.toNamed("/third/child-of-third");
Run Code Online (Sandbox Code Playgroud)

出现错误的原因是当您在 GetX 中使用外部路由插件时,它会生成自己的代码,在自己的生态系统中具有自己的上下文。GetX 不知道插件使用哪个上下文,因为它超出了其生命周期。