Flutter,不知道如何实现PageRouteBuilder(),当使用WidgetBuilder来配置我的路由时。

问题描述 投票:0回答:1
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: codGray,
      body: Navigator(
        key: _navigatorKey,
        initialRoute: '/',
        onGenerateRoute: (RouteSettings settings) {
          WidgetBuilder builder;
          // Manage your route names here
          switch (settings.name) {
            case '/':
              builder = (BuildContext context) => ProviderPage();
              break;
            case '/chats':
              builder = (BuildContext context) => ChatProviderPage();
              break;
            case '/addPoll':
              builder = (BuildContext context) => AddPollPage();
              break;
            case '/friends':
              builder = (BuildContext context) => ProfileProviderPage();
              break;
            case '/settings':
              builder = (BuildContext context) => SettingsProviderPage();
              break;
            default:
              throw Exception('Invalid route: ${settings.name}');
          }
          return MaterialPageRoute(
            builder: builder,
            settings: settings,
          );
        },
      ),
}

这是我的项目的一个片段,我试图在页面之间过渡时实现自定义的动画,但是由于我使用自定义的导航器进行路由,而导航器使用WidgetBuilder,我不知道如何实现自定义的PageRouteBuilder(),它使用WidgetBuilder构建器在页面之间过渡。

flutter flutter-animation
1个回答
0
投票

你可以通过直接返回 MaterialPageRoutePageRouteBuilder 像这样。

Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: codGray,
      body: Navigator(
        key: _navigatorKey,
        initialRoute: '/',
        onGenerateRoute: (RouteSettings settings) {
          switch (settings.name) {
            case '/':
              return MaterialPageRoute(
                builder: (BuildContext context) => ProviderPage(),
                settings: settings,
              );
            case '/chats':
              return MaterialPageRoute(
                builder: (BuildContext context) => ChatProviderPage(),
                settings: settings,
              );
            case '/customTransition':
              return PageRouteBuilder(
                pageBuilder: (context, animation, secondaryAnimation) => Page(),
                transitionsBuilder: (context, animation, secondaryAnimation, child) {
                  return child;
                },
              );
            default:
              throw Exception('Invalid route: ${settings.name}');
          }
        },
      ),
}

虽然你可以在这里重构很多东西,使它更易读和维护。

  1. 你可以提取出这个函数给 onGenerateRoute 争论中 Navigator 小部件
  2. 使用常量作为路由。这使得它的可读性强,减少了因为错别字而产生的错误。
  3. 你可以创建扩展 PageRouteBuilder 与你自己的班级,这需要一个子论点的 Widget 类型,其余所有的转换逻辑都在该类中。
© www.soinside.com 2019 - 2024. All rights reserved.