Flutter-实现抽屉动画
在Flutter中,实现抽屉动画可以使用Drawer
组件和AnimationController
。以下是一个简单的例子:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
AnimationController _controller;
Animation<Offset> _offsetAnimation;
final double _drawerMaxWidth = 200.0;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 200),
);
_offsetAnimation = Tween<Offset>(
begin: Offset.zero,
end: Offset(_drawerMaxWidth / MediaQuery.of(context).size.width, 0),
).animate(_controller);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggleDrawer() {
if (_controller.status == AnimationStatus.completed) {
_controller.reverse();
} else {
_controller.forward();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Drawer Animation Example'),
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: _toggleDrawer,
),
),
body: Center(
child: Text('Tap on menu button to open drawer'),
),
drawer: SlideTransition(
position: _offsetAnimation,
child: Drawer(
child: Container(
width: _drawerMaxWidth,
child: ListView(
children: <Widget>[
ListTile(
title: Text('Item 1'),
onTap: _toggleDrawer,
),
ListTile(
title: Text('Item 2'),
onTap: _toggleDrawer,
),
// ... more list items
],
),
),
),
),
);
}
}
在这个例子中,我们定义了一个_toggleDrawer
方法来切换抽屉的打开和关闭状态。通过SlideTransition
来实现位置动画,并
评论已关闭