gpt4 book ai didi

flutter - 如何从 Flutter 中的另一个小部件访问有状态的小部件动画 Controller ?

转载 作者:行者123 更新时间:2023-12-02 00:08:19 25 4
gpt4 key购买 nike

我希望计数器小部件显示来自主页 widgetonTap。此外,在每次点击时从头开始播放动画

计数器小工具

class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> with SingleTickerProviderStateMixin {
AnimationController animationController;
Animation<double> animation;

@override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 1000),
)
..addListener(() => setState(() {}));

animation = CurvedAnimation(
parent: animationController,
curve: Curves.elasticOut,
);

animationController.forward();
}

@override
Widget build(BuildContext context) {
return ScaleTransition(
child: Container(
height: 100,
width: 100,
color: Colors.blue,
),
scale: animation,
);
}
}

主页小工具

  @override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Center(
child: Counter(),
),
GestureDetector(
onTap: () {},
child: Container(
width: double.infinity,
height: double.infinity,
),
),
],
));
}

最佳答案

您需要定义一个 GlobalKey 并将其传递给子部件。这将使您能够访问该 Child 的方法和变量:

class HomeWidget extends StatefulWidget {
@override
_HomeWidgetState createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
GlobalKey<CounterState> counterKey = GlobalKey<CounterState>();

@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
Center(
child: Counter(key: counterKey),
),
GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
counterKey.currentState.animationController.reverse();
},
child: Container(
width: double.infinity,
height: double.infinity,
),
),
],
)
);
}
}


class Counter extends StatefulWidget {
Counter({Key key}): super(key: key);

// This state must be public in order to access it.
@override
CounterState createState() => CounterState();
}

class CounterState extends State<Counter> with SingleTickerProviderStateMixin {
AnimationController animationController;
Animation<double> animation;

@override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 1000),
)
..addListener(() => setState(() {}));

animation = CurvedAnimation(
parent: animationController,
curve: Curves.elasticOut,
);

animationController.forward();
}

@override
Widget build(BuildContext context) {
return ScaleTransition(
child: Container(
height: 100,
width: 100,
color: Colors.blue,
),
scale: animation,
);
}
}

关于flutter - 如何从 Flutter 中的另一个小部件访问有状态的小部件动画 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59857743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com