解决方案:将AnimatedBuilder包裹在如Center的布局约束中
关键代码:
class GrowTransition extends StatelessWidget {
GrowTransition({required this.child, required this.animation});
late final Widget child;
late final Animation<double> animation;
@override
Widget build(BuildContext context) => Center(
child: AnimatedBuilder(
animation: animation,
builder: (context, child) => Container(
child: child,
height: animation.value,
width: (animation).value,
),
child: child,
),
);
}
完整代码:
import 'package:flutter/material.dart';
///这是一个使用AnimatedBuilder拆分动画的,实现动画和widget进行分离的实例
class AniBuilder extends StatefulWidget {
@override
_AniBuilder createState() => _AniBuilder();
}
class _AniBuilder extends State<AniBuilder>
with SingleTickerProviderStateMixin {
Animation<double>? animation;
AnimationController? controller;
@override
void initState() {
super.initState();
controller =
AnimationController(vsync: this, duration: Duration(seconds: 2));
animation = Tween<double>(begin: 0, end: 300).animate(controller!);
controller!.forward();
}
@override
Widget build(BuildContext context) {
Widget aniPlayerContainer = AniBuilderWidget().build(context);
///这种写法将AniBuilderWidget与GrowTransition分离,
///GrowTransition用于动画的播放的设置
///AniBuilderWidget用于设定播发动画的组件
return new GrowTransition(
child: Container(child: (aniPlayerContainer as Container).child),
animation: (animation as Animation<double>));
}
@override
void dispose() {
controller!.dispose();
super.dispose();
}
}
class AniBuilderWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: FlutterLogo(),
);
}
}
class GrowTransition extends StatelessWidget {
GrowTransition({required this.child, required this.animation});
late final Widget child;
late final Animation<double> animation;
@override
Widget build(BuildContext context) => Center(
child: AnimatedBuilder(
animation: animation,
builder: (context, child) => Container(
child: child,
height: animation.value,
width: (animation).value,
),
child: child,
),
);
}
参考链接:
1.?https://flutterchina.club/layout/
2.?https://blog.csdn.net/ShuSheng0007/article/details/110292757
3.?https://coding.imooc.com/learn/questiondetail/pylDvPyAVlgPkBNm.html
|