如何去除默认导航路线动画

问题描述 投票:0回答:6

我在页面路由的 flutter 文档中给出的代码下面

// Within the `FirstRoute` widget
onPressed: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondRoute()),
  );
}

但是它在推送和弹出路线时提供了一些动画。

对于Android,页面入口过渡滑动页面 向上并淡入。退出过渡是相同的,但在 反转。

转场自适应平台,在iOS上,页面滑动 从右边进来,反向出去。页面也转移到 当另一页进入以覆盖它时,它处于视差状态。 (这些 在从右到左阅读的环境中方向被翻转 方向。)

有什么方法可以在没有任何动画的情况下路由到下一页吗?

编辑: 请检查整个代码:

class MyApp extends StatelessWidget {
  final routes = <String, WidgetBuilder>{
    SecondRoute.tag: (context) => SecondRoute(),
  };

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Routes",
      home: new FirstRoute(),
      routes: routes,
      onGenerateRoute: (routeSettings) {
        if (routeSettings.name == SecondRoute.tag)
          return PageRouteBuilder(pageBuilder: (_, a1, a2) => SecondRoute());

        return null;
      },
    );
  }
}

class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Route'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Open route'),
          onPressed: () {
            Navigator.of(context).pushNamed(SecondRoute.tag);

          },
        ),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  static String tag = 'second-route';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}
flutter flutter-animation flutter-navigation
6个回答
20
投票
  • 对于
    Navigator.push(...)

    Navigator.push(
      context,
      PageRouteBuilder(pageBuilder: (_, __, ___) => SecondRoute()),
    )
    
  • 对于
    Navigator.pushNamed(...)

    首先,将此添加到您的

    MaterialApp

    MaterialApp(
      onGenerateRoute: (settings) {
        if (settings.name == '/second') 
          return PageRouteBuilder(pageBuilder: (_, __, ___) => SecondRoute());
    
        return null;
      },
    )
    

    现在,您可以使用:

    Navigator.pushNamed(context, '/second');
    

11
投票

动画由

MaterialPageRoute
表演。如果你不想要它,简单地使用其他东西:

Navigator.push(
  context,
  PageRouteBuilder(pageBuilder: (_, __, ___) => MyRoute()),
)

2
投票

用这个替换你的

MyApp

class MyApp extends StatelessWidget {
  final routes = <String, WidgetBuilder>{SecondRoute.tag: (context) => SecondRoute()};

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Routes",
      home: new FirstRoute(),
      onGenerateRoute: (routeSettings) {
        if (routeSettings.name == SecondRoute.tag)
          return PageRouteBuilder(
            pageBuilder: (_, a1, a2) => FadeTransition(opacity: a1 ,child: SecondRoute()),
            transitionDuration: Duration(seconds: 5),
          );

        return null;
      },
    );
  }
}

2
投票

由于 Flutter 现在正在迁移到 Navigator 2.0 以获得更多支持,我建议您查看他们的迁移指南,了解如何向 Navigator 添加 TransitionDelegate。将此类的实例添加到您的导航器以实现预期结果:

import 'package:flutter/widgets.dart';

class NoAnimationTransitionDelegate extends TransitionDelegate<void> {
  @override
  Iterable<RouteTransitionRecord> resolve({
    List<RouteTransitionRecord> newPageRouteHistory,
    Map<RouteTransitionRecord, RouteTransitionRecord> locationToExitingPageRoute,
    Map<RouteTransitionRecord, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
  }) {
    final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];

    for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
      // Renames isEntering to isWaitingForEnteringDecision.
      if (pageRoute.isWaitingForEnteringDecision) {
        pageRoute.markForAdd();
      }
      results.add(pageRoute);

    }
    for (final RouteTransitionRecord exitingPageRoute in locationToExitingPageRoute.values) {
      // Checks the isWaitingForExitingDecision before calling the markFor methods.
      if (exitingPageRoute.isWaitingForExitingDecision) {
        exitingPageRoute.markForRemove();
        final List<RouteTransitionRecord> pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute];
        if (pagelessRoutes != null) {
          for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
            pagelessRoute.markForRemove();
          }
        }
      }
      results.add(exitingPageRoute);

    }
    return results;
   }
 }

0
投票

aidan marshal 的解决方案很简单并且工作正常但是他的代码有一些调整

 import 'package:flutter/widgets.dart';

class NoAnimationTransitionDelegate extends TransitionDelegate<void> {

   @override
   Iterable<RouteTransitionRecord> resolve({
       required List<RouteTransitionRecord> newPageRouteHistory,
       required Map<RouteTransitionRecord?, RouteTransitionRecord> 
       locationToExitingPageRoute, required Map<RouteTransitionRecord?, 
      List<RouteTransitionRecord>> pageRouteToPagelessRoutes}) {
    {
     final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];

     for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
      // Renames isEntering to isWaitingForEnteringDecision.
      if (pageRoute.isWaitingForEnteringDecision) {
        pageRoute.markForAdd();
      }
      results.add(pageRoute);

    }
    for (final RouteTransitionRecord exitingPageRoute in locationToExitingPageRoute.values) {
      // Checks the isWaitingForExitingDecision before calling the markFor methods.
      if (exitingPageRoute.isWaitingForExitingDecision) {
        exitingPageRoute.markForRemove();
        final List<RouteTransitionRecord>? pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute];
        if (pagelessRoutes != null) {
          for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
            pagelessRoute.markForRemove();
          }
        }
      }
      results.add(exitingPageRoute);

    }
    return results;
   }
  }
 }

0
投票

如果您使用路由,这里是获得永久解决方案的完整代码

      void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      await ScreenUtil.ensureScreenSize();
      await ServiceLocator.setUpServiceLocator();
      initializeLoggerServer();
      serviceLocator.get<Log>().shout('App Initialized Successfully');
      runApp(AgrotopiaApp());
    }
    
    void initializeLoggerServer() {
      Logger.root.level = Level.ALL; // defaults to Level.INFO
      Logger.root.onRecord.listen((record) {
        debugPrint('${record.level.name}: ${record.time}: ${record.message}');
      });
    }
      //create this class to make no animation 
    class NoAnimationPageRoute<T> extends MaterialPageRoute<T> {
      NoAnimationPageRoute({required WidgetBuilder builder, required RouteSettings settings})
          : super(builder: builder, settings: settings);
    
      @override
      Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
        return FadeTransition(opacity: AlwaysStoppedAnimation(1.0), child: child);
      }
    }
    
   
    class FadePageRoute<T> extends MaterialPageRoute<T> {
      FadePageRoute({required WidgetBuilder builder, required RouteSettings settings})
          : super(builder: builder, settings: settings);
    
      @override
      Widget buildTransitions(BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation, Widget child) {
        return FadeTransition(opacity: animation, child: child);
      }
    }
    
    
    class AgrotopiaApp extends StatelessWidget {
      AgrotopiaApp({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return ScreenUtilInit(
            designSize: context.resources.variables.screenDesignSize,
            splitScreenMode: false,
            minTextAdapt: true,
            useInheritedMediaQuery: false,
            builder: (BuildContext context, Widget? child) {
              return MultiProvider(
                providers: [
                  ChangeNotifierProvider(
                      create: (_) => LoaderModelView(), lazy: true),
                  ChangeNotifierProvider(
                      create: (_) => GlobalAppProvider(), lazy: true),
                  ChangeNotifierProvider(
                      create: (_) => OnBoardingViewModel(), lazy: true),
                  ChangeNotifierProvider(
                      create: (_) => BottomNavViewModel(), lazy: true),
                  ChangeNotifierProvider(
                      create: (_) => PlaceOrderViewModel(), lazy: true),
                  ChangeNotifierProvider(
                      create: (_) => PaymentViewModel(), lazy: true),
                ],
                child: MaterialApp(
                    navigatorKey: GlobalKey<NavigatorState>(),
                    title: context.resources.variables.appName,
                    debugShowCheckedModeBanner: false,
                    theme: context.resources.styles.appTheme(),
                    home: const SplashScreen(),
                    // home: CollectUserData(),
                    // home: const UserOnBoardingPage(),
                    initialRoute: '/',
                     onGenerateRoute: (RouteSettings settings) {
                      
            switch (settings.name) {
              
              case '/home':
                return NoAnimationPageRoute(builder: (_) => HomePage(), settings: settings);
              case '/app':
                return NoAnimationPageRoute(builder: (_) => AgrotopiaApp(), settings: settings);
              case '/settingpage':
                return NoAnimationPageRoute(builder: (_) => SettingPage(), settings: settings);
              case '/placeordermenu':
                return NoAnimationPageRoute(builder: (_) => PlaceOrderMenu(), settings: settings);
              case '/placeorderpage':
                return NoAnimationPageRoute(builder: (_) => PlaceOrderPage(), settings: settings);
              case '/paymentinformationpage':
                return NoAnimationPageRoute(builder: (_) => PaymentInformationPage(), settings: settings);
              case '/orderstatuspage':
                return NoAnimationPageRoute(builder: (_) => OrderStatusPage(), settings: settings);
              case '/orderdetailspage':
                return NoAnimationPageRoute(builder: (_) => OrderDetailsPage(), settings: settings);
              case '/confirmation':
                return NoAnimationPageRoute(builder: (_) => Confirmation(), settings: settings);
              // case '/orderdetailspage':
              //   return NoAnimationPageRoute(builder: (_) => OrderDetailsPage(), settings: settings);
              default:
                return MaterialPageRoute(builder: (_) => Scaffold());
            }
          },
                    
            
                    ),
              );
            });
      }
    }

现在导航到另一个页面

  Navigator.pushNamed(context,'/orderstatuspage');
© www.soinside.com 2019 - 2024. All rights reserved.