问题描述
我有一个 Row
窗口小部件,该窗口小部件在其一个单元格中保存了一个子窗口小部件(其他单元格中则保存了 Spacer()
).根据状态,保存子控件的单元格会发生变化,从而导致子控件的位置发生变化.我想动画化此动作以使其顺畅.是否可以使用标准动画小部件(例如 AnimatedPositioned
,在这种情况下将无法正常工作)来做到这一点?
I have a Row
Widget that holds a child Widget in one of its cells (the others hold a Spacer()
). Depending on the state, the cell which holds the child changes, resulting in a position change of the child Widget. I want to animate this motion to make it smooth. Is there a way of doing so with the standard animation Widgets (something like AnimatedPositioned
, which won't work in this case)?
推荐答案
如果在行中插入堆栈,则可以使用AnimatedPositioned.否则,可以将 AnimatedBuilder
与 Transform.translate
一起使用,并在小部件的X轴上设置 Offset
的动画.下面有一个完整的示例,您可以在 DartPad 上运行以查看结果.希望对您有所帮助.
You could use AnimatedPositioned if you insert a Stack inside your row.Otherwise, you can use an AnimatedBuilder
with Transform.translate
and animate the Offset
on the axis X of your widget. Bellow there's a complete example, that you can run at DartPad to see the result. Hope it helps.
import 'package:flutter/material.dart';
void main(){
runApp(MaterialApp(home: MyAnimation()));
}
class MyAnimation extends StatefulWidget {
@override
_MyAnimationState createState() => _MyAnimationState();
}
class _MyAnimationState extends State<MyAnimation> with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> animation;
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: Duration(milliseconds: 5000));
animation = Tween(begin: 0.0, end: 300.0).animate(_controller);
_controller.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Title")),
body: AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Row(
children: <Widget>[
Transform.translate(
child: Container(width: 100, height: 100, color: Colors.black),
offset: Offset(animation.value, 0),
),
Container(width: 100, height: 100, color: Colors.transparent),
Container(width: 100, height: 100, color: Colors.transparent),]
);
},
),
);
}
}
这篇关于在Flutter中跨行单元设置动画位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!