Flutter 动画切换组件(AnimatedSwitcher)
封面图
•
2025-11-08
•
Flutter
0
0
0
0
在 Flutter 中,`AnimatedSwitcher` 是一个非常有用的组件,用于在不同子组件之间进行**平滑的动画切换**。它非常适合用于需要在多个 UI 状态之间切换的场景,比如导航菜单、选项卡切换、状态变化等。 --- ## ✅ `AnimatedSwitcher` 的基本用法 ```dart import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('AnimatedSwitcher Example')), body: Center(child: MyAnimatedSwitcher()), ), ); } } class MyAnimatedSwitcher extends StatefulWidget { @override _MyAnimatedSwitcherState createState() => _MyAnimatedSwitcherState(); } class _MyAnimatedSwitcherState extends State<MyAnimatedSwitcher> { bool _showText = true; void _toggleText() { setState(() { _showText = !_showText; }); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ AnimatedSwitcher( duration: const Duration(seconds: 1), child: _showText ? Text('Hello, Flutter!', key: UniqueKey()) : Text('Goodbye!', key: UniqueKey()), ), SizedBox(height: 20), ElevatedButton( onPressed: _toggleText, child: Text(_showText ? 'Hide' : 'Show'), ), ], ); } } ``` --- ## 🔍 参数说明 | 参数 | 类型 | 说明 | |------|------|------| | `duration` | `Duration` | 动画持续时间 | | `switchInAnimation` | `Animation<double>` | 子组件进入时的动画(默认是 `fade`) | | `switchOutAnimation` | `Animation<double>` | 子组件退出时的动画(默认是 `fade`) | | `child` | `Widget` | 要显示的当前子组件 | | `key` | `Key` | 必须为每个子组件提供唯一 key,否则动画不会生效 | --- ## 🎨 自定义动画 你可以使用 `FadeTransition`、`SlideTransition` 或自定义动画来实现更丰富的效果。 ### 示例:使用 `SlideTransition` ```dart AnimatedSwitcher( duration: const Duration(milliseconds: 500), transitionBuilder: (child, animation) { return FadeTransition( opacity: animation, child: SlideTransition( position: Tween<Offset>( begin: Offset.zero, end: Offset(1.0, 0.0), ).animate(animation), child: child, ), ); }, child: _showText ? Text('Hello') : Text('Bye'), ), ``` --- ## 📌 注意事项 - **必须给每个子组件设置唯一的 `key`**,否则 `AnimatedSwitcher` 无法识别是“同一个组件”还是“新组件”。 - 如果你不想使用默认的淡入淡出动画,可以自定义 `transitionBuilder`。 - `AnimatedSwitcher` 只能包含一个子组件,不能直接嵌套多个组件。 --- ## 🧠 常见应用场景 - 页面切换(如 TabBar 切换) - 动态内容加载(如从网络加载数据时的过渡) - 状态切换(如登录/注册页面切换) --- 如果你有具体的使用场景或想要实现的效果,欢迎告诉我,我可以帮你定制代码 😊
上一篇:
iOS开发 应用程序调试
标题录入,一次不能超过6条
留言
评论