使用GetX的Flutter动画控制器



我最近切换到GetX,希望在GetxController中初始化动画控制器,并可以在GetView中访问它。当应用程序启动时,动画可以顺利进行,但无法再次转发。

class SplashController extends GetxController with GetTickerProviderStateMixin {
var h = 0.0.obs;
late AnimationController ac;
late Animation animation;
Future<void> initAnimation() async {
ac = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
);
animation = Tween(begin: 0.0, end: 1.0).animate(ac);
}
forwardAnimationFromZero() {
ac.forward(from: 0);
}
@override
void onInit() {
super.onInit();
initAnimation();
forwardAnimationFromZero();
ac.addListener(() {
h.value = animation.value;
});
}
@override
void onReady() {
super.onReady();
forwardAnimationFromZero();
}
@override
void onClose() {
super.onClose();
ac.dispose();
}
}

正如你所看到的,我扩展了GetxController with GetTickerProviderStateMixin,但股票行情器不能正常工作。我把var h = 0.0.obs;定义为可观察的,所以可以在屏幕上访问,没有它动画就不会滴答作响!

class SplashPage extends GetView<SplashController> {
const SplashPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var c = Get.put(SplashController());
return Scaffold(
body: Column(
children: [
Container(
color: Colors.amber,
width: (controller.animation.value * 100) + 100,
height: (controller.animation.value * 100) + 100,
child: Center(
child: Text(
controller.animation.value.toString(),
),
),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
c.ac.forward(from: 0);
},
child: Icon(Icons.refresh),
),
appBar: AppBar(
title: const Text('Splash Page'),
),
);
}
}

在这个视图中,当动画开始时没有反应,但当我hot relaod时,我看到它处于结束状态。将Container小部件更改为:时

Obx(
() => Container(
color: Colors.amber,
width: (controller.animation.value * 100) + 100,
height: (controller.h.value * 100) + 100,
child: Center(
child: Text(
controller.animation.value.toString(),
),
),
),
),

在开始时重新设置为CCD_ 7动画播放,但当我按下CCD_。我想要什么:

  1. 为什么动画在没有h可观察的情况下一开始就不播放
  2. 如何访问视图中的动画控制器功能
  3. 当某个动画控制器完成时,我想启动另一个动画控制器

在此部分中使用动画容器。因为随着代码的增长,写得太长会减慢你的工作速度。

控制器

class SplashController extends GetxController {
var h = 40.0.obs;
}

页面

class SplashPage extends GetView<SplashController> {
var click = true;
@override
Widget build(BuildContext context) {
return GetBuilder<SplashController>(
init: Get.put(SplashController()),
builder: (cnt) {
return Center(
child: PageView(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ElevatedButton(
child: Text('Animate!'),
onPressed: () {
click
? cnt.h.value = 250.0
: cnt.h.value = 50.0;
click = !click;
},
),
Obx(
() => AnimatedContainer(
duration: Duration(seconds: 1),
width: cnt.h.value,
height: 40,
color: Colors.red,
),
),
],
)
],
),
);
}
);
}
}

当您的代码是StatelessWidget时,以下代码用于更新您的代码。

Obx(
() => AnimatedContainer(
duration: Duration(seconds: 1),
width: cnt.h.value,
height: 40,
color: Colors.red,
),
),

每次单击按钮,您都可以放大和缩小。

最新更新