Flutter:如何在导航时实现缩放动画

问题描述 投票:0回答:1
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});

@override
State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
Future.delayed(Duration(seconds: 3), () {
  Navigator.of(context).push(
    MaterialPageRoute(
      builder: (context) => LoginScreen(),
    ),
  );
});
super.initState();
}

@override
Widget build(BuildContext context) {
return Scaffold(
  body: Center(
    child: Image.asset("assets/logo.png"),
  ),
);
}
}

我有一个启动屏幕,3 秒后它将导航到登录屏幕。导航时,我需要缩放图像,然后会出现下一个屏幕。我怎样才能实现它。任何人请帮我做到这一点..

flutter dart animation flutter-animation
1个回答
0
投票

尝试用下面给出的代码替换 _SplashScreenState

class _SplashScreenState extends State<SplashScreen> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(
        parent: _controller,
        curve: Curves.easeInOut,
      ),
    );

    _controller.forward();

    Future.delayed(Duration(seconds: 2), () {
      if (mounted) {
        Navigator.of(context).pushReplacement(
          ZoomPageRoute(
            page: LoginScreen(),
          ),
        );
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ScaleTransition(
          scale: _animation,
          child: Image.asset("assets/logo.png"),
        ),
      ),
    );
  }
}

对于缩放效果使用下面的代码

class ZoomPageRoute extends PageRouteBuilder {
  final Widget page;

  ZoomPageRoute({required this.page})
      : super(
          pageBuilder: (context, animation, secondaryAnimation) => page,
          transitionsBuilder: (context, animation, secondaryAnimation, child) {
            const begin = 0.0;
            const end = 1.0;
            const curve = Curves.easeInOut;

            var scaleTween = Tween<double>(begin: begin, end: end)
                .chain(CurveTween(curve: curve));

            var scaleAnimation = animation.drive(scaleTween);

            return ScaleTransition(
              scale: scaleAnimation,
              child: child,
            );
          },
        );
}
© www.soinside.com 2019 - 2024. All rights reserved.