我正在使用 flutter_animate 将淡入淡出动画应用到我的全屏覆盖小部件。
动画“打开”覆盖层就像添加一行代码一样简单,如
Animate(effects: const [FadeEffect()], child: const AddOverlay()),)
但是,我不知道如何在使用
Navigator.of(context).pop(context);
关闭叠加层时反转淡入淡出效果
下面是最小的可重现代码,带有默认的样板 flutter 项目。
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
body: const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Animated Transition',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(
PageRouteBuilder(
opaque: false,
pageBuilder: (BuildContext context, _, __) => Animate(
effects: const [FadeEffect()],
child:
const AddOverlay()), // Using flutter_animate package to add animation to opening the overlay widget
),
);
},
child: const Icon(Icons.add),
),
);
}
}
class AddOverlay extends StatelessWidget {
const AddOverlay({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black.withOpacity(0.85),
body: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 5.0,
sigmaY: 5.0,
),
child: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pop(
context); // Closing the overlay should also have a fade animation effect.
},
child: const Text("Close"))),
),
);
}
}
我不明白为什么我们需要在这种情况下使用
flutter_animate
。您可以通过使用内置的 FadeTransition
小部件与 pageTransitionBuilder
结合使用来达到所需的效果,它允许您在页面 push
或 pop
过渡期间自定义动画。推送时,动画值会从0到1.0,弹出路线时,动画值会反转。
自定义转换的路由部分:
void _navigateToAddOverlay(BuildContext context) {
Navigator.of(context).push(
PageRouteBuilder(
opaque: false,
reverseTransitionDuration: const Duration(seconds: 5),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
pageBuilder: (_, __, ___) => const AddOverlay(),
),
);
}
这是完整更新的代码:https://zapp.run/edit/flutter-zk3e0614k3f0?entry=lib/main.dart&file=lib/main.dart