flutter如何在里面实现动画class GetView<Controller>

flutter how to implement animation inside class GetView<Controller>

我正在开始一个 flutter 项目,很多人说 GetX 是 flutter 中最好用的状态管理器框架,所以我决定使用它。

我想在 class 主页中做一些动画,但是当我使用 mixin SingleTickerProviderStateMixin 时,它会抛出一个编译错误

error: 'SingleTickerProviderStateMixin<StatefulWidget>' can't be mixed onto 'GetView<HomePageController>' because 'GetView<HomePageController>' doesn't implement 'State<StatefulWidget>'.

这是我的代码

class HomePage extends GetView<HomePageController> with SingleTickerProviderStateMixin {
  final Duration duration = const Duration(milliseconds: 300);
  AnimationController _animationController;

  HomePage() {
     _animationController = AnimationController(vsync: this, duration: duration);
  }

  @override
  Widget build(BuildContext context) {
     return Container();
  } 

}

因为要初始化一个AnimationController,它需要一个名为'vsync'的参数,所以我必须实现mixin SingleTickerProviderStateMixin。但是因为 GetView<> 没有实现 State 所以它抛出编译错误。

我不知道在 GetX 中实现动画的正确方法是什么,奇怪的是我在 Google 或任何 flutter 社区上找不到任何线索或指南,尽管有广泛的GetX

的受欢迎程度

尝试使用 SingleTickerProviderStateMixin 的 GetX 版本 - SingleGetTickerProviderMixin:

class HomePage extends GetView<HomePageController> with SingleGetTickerProviderMixin {

}

您想在您的控制器 class 上使用 with SingleGetTickerProviderMixin,而不是您的实际页面。这是 GetX 特有的,允许您在无状态小部件上使用动画控制器。

class HomePageController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final Duration duration = const Duration(milliseconds: 300);

  AnimationController animationController;

  @override
  void onInit() {
    super.onInit();
    animationController = AnimationController(vsync: this, duration: duration);
  }
}

然后在扩展 GetView<HomePageController> 的页面中使用 controller.animationController 访问动画控制器。

class HomePage extends GetView<HomePageController> 
  @override
  Widget build(BuildContext context) {
// access animation controller on this page with controller.animationController
     return Container();
  } 

}

只需确保您的 HomePageController 在主页加载前已完全初始化。如果 HomePage 是您应用程序中的第一件事,那么保证在 HomePage 尝试加载之前对其进行初始化的一种方法是使用 GetX [=] 中的 Future 方法初始化控制器34=].

 Future<void> initAnimationController() async {
    animationController = AnimationController(vsync: this, duration: duration);
  }

然后在你的main方法中初始化。

void main() async {
  final controller = Get.put(HomePageController());
  await controller.initAnimationController();

  runApp(MyApp());
}

根据我的经验,如果您在应用程序加载的第一页中使用来自 Getx class 的动画控制器,在 onInit 中初始化并不能保证它会成功准备好并可能会抛出错误。在 main 中使用 Future 方法和 await 将确保您不会收到未初始化的错误。