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('Animated Container')),
body: AnimatedContainerExample(),
),
);
}
}
class AnimatedContainerExample extends StatefulWidget {
@override
_AnimatedContainerExampleState createState() => _AnimatedContainerExampleState();
}
class _AnimatedContainerExampleState extends State<AnimatedContainerExample> {
double _height = 100.0;
void _toggleHeight() {
setState(() {
_height = _height == 100.0 ? 200.0 : 100.0; // 切換高度
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedContainer(
duration: Duration(seconds: 1), // 動(dòng)畫持續(xù)時(shí)間
height: _height,
width: 100,
color: Colors.blue,
curve: Curves.easeInOut, // 動(dòng)畫曲線
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _toggleHeight,
child: Text('Toggle Height'),
),
],
),
);
}
}
代碼說明:
AnimatedContainer: 這個(gè)小部件會(huì)自動(dòng)為你提供一個(gè)動(dòng)畫效果,當(dāng)它的屬性(在這里是 height)發(fā)生變化時(shí)倒戏。
duration: 設(shè)置動(dòng)畫的持續(xù)時(shí)間,這里設(shè)置為 1 秒棚瘟。
curve: 你可以設(shè)置動(dòng)畫的曲線效果留荔,例如 Curves.easeInOut 使得動(dòng)畫在開始和結(jié)束時(shí)都比較平滑。
_toggleHeight 方法: 點(diǎn)擊按鈕會(huì)調(diào)用這個(gè)方法讨阻,切換 _height 的值芥永,并觸發(fā)動(dòng)畫。
使用方法:
將上述代碼復(fù)制到你的 Flutter 項(xiàng)目中并運(yùn)行钝吮,點(diǎn)擊按鈕即可看到容器的高度在 100 和 200 之間變化的動(dòng)畫效果埋涧。