當前正在運行的影片(未完成或取消)時是否可以監聽子小部件位置的變化?例如我們有這個變數:
GlobalKey globalKey= GlobalKey();
bool isAnimated =false;
我需要在這個 AnimatedContainer 中監聽目標小部件的位置:
InkWell(
onTap:() => setState(() {isAnimated=!isAnimated};) ,
child: AnimatedContainer(
duration: Duration(milliseconds: 1000),
width: 200,
height: isAnimated?100:40,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
SizedBox(height: 10,),
//the target widget
SizedBox(
key: globalKey,
)
],)
),
)
例如當 AnimatedContainer 的高度達到 70 時,它會根據目標小部件的位置確認我做某事。
uj5u.com熱心網友回復:
您的確切要求尚不清楚。根據“對目標小部件執行操作”的含義,您可能需要選擇不同的方法。但是,如果您想為影片添加偵聽器或對當前影片值做出反應,最好使用AnimatedBuilder。我包括一個可以幫助您解決問題的基本示例。
class MyAnimatedWidget extends StatefulWidget {
const MyAnimatedWidget({
Key? key,
}) : super(key: key);
@override
State<MyAnimatedWidget> createState() => _MyAnimatedWidgetState();
}
class _MyAnimatedWidgetState extends State<MyAnimatedWidget>
with TickerProviderStateMixin {
late final AnimationController _controller;
late Animation _animation;
GlobalKey globalKey = GlobalKey();
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1000),
);
_controller.addListener(() {
//also possible to listen for changes with a listener
});
_animation = CurveTween(curve: Curves.easeOut).animate(_controller);
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return InkWell(
onTap: () {},
child: Container(
width: 200,
height: _containerHeightBuilder(_controller.value),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const SizedBox(
height: 10,
),
//the target widget
SizedBox(
//or do something here with the current animation value
key: globalKey,
)
],
)),
);
});
}
double _containerHeightBuilder(double animationValue) {
const double containerAnimationTarget = 60;
const double containerBaseHeight = 40;
const double thresholdHeight = 70;
double currentHeight =
containerBaseHeight (containerAnimationTarget * animationValue);
if (currentHeight == thresholdHeight) {
//do something here
}
return currentHeight;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459087.html
