在使用隐式动画组件的时候,最常用的组件之一是AnimatedContainer
。这篇博客来分享AnimatedContainer
相关的知识,希望对你有所启发。
AnimatedContainer使用示例
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'AnimatedContainer Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double width = 100;
double height = 100;
Color backgroundColor = Colors.redAccent;
void startAnimation() {
setState(() {
width = 300;
height = 300;
backgroundColor = Colors.yellowAccent;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: AnimatedContainer(
width: width,
height: height,
color: backgroundColor,
duration: Duration(microseconds: 2000),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 点击事件,设置动画开始
startAnimation();
},
child: const Icon(Icons.play_arrow),
),
);
}
}
效果如下图所示:
初始化状态 动画执行后
源码
AnimatedContainer({
Key? key,
this.alignment,
this.padding,
Color? color,
Decoration? decoration,
this.foregroundDecoration,
double? width,
double? height,
BoxConstraints? constraints,
this.margin,
this.transform,
this.transformAlignment,
this.child,
this.clipBehavior = Clip.none,
Curve curve = Curves.linear,
required Duration duration,
VoidCallback? onEnd,
}) : assert(margin == null || margin.isNonNegative),
assert(padding == null || padding.isNonNegative),
assert(decoration == null || decoration.debugAssertIsValid()),
assert(constraints == null || constraints.debugAssertIsValid()),
assert(color == null || decoration == null,
'Cannot provide both a color and a decoration\n'
'The color argument is just a shorthand for "decoration: BoxDecoration(color: color)".',
),
decoration = decoration ?? (color != null ? BoxDecoration(color: color) : null),
constraints =
(width != null || height != null)
? constraints?.tighten(width: width, height: height)
?? BoxConstraints.tightFor(width: width, height: height)
: constraints,
super(key: key, curve: curve, duration: duration, onEnd: onEnd);
属性说明:
属性名称 | 详情说明 |
---|---|
alignment | 对齐方式 |
padding | 外间距 |
color | 容器颜色 |
Decoration | Decoration对象 |
width | 宽度 |
height | 高度 |
margin | 内间距 |
child | 子组件 |
网友评论