flutter 如何在 GetView<Controller> 类中实现动画

标签 flutter animation mixins flutter-getx

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

我想在 HomePage 类中做一些动画,但是当我使用 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 广受欢迎

最佳答案

您想使用 with GetSingleTickerProviderStateMixin在您的 Controller 类上,而不是您的实际页面上。这是 GetX 特有的,允许您在无状态小部件上使用动画 Controller 。

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 访问动画 Controller .

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

}

只需确保您的 HomePageController在 HomePage 加载之前完全初始化。如果HomePage是您应用程序中的第一件事,然后是保证其在 HomePage 之前初始化的一种方法尝试加载是用 Future 初始化 Controller GetX 类中的方法。

 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 类的动画 Controller ,则在 onInit 中初始化不能保证它会准备好并可能会抛出错误。使用 Future方法和await in main 将确保您不会收到未初始化的错误。

关于 flutter 如何在 GetView<Controller> 类中实现动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67354729/

相关文章:

flutter - 在 Flutter 中创建自定义小部件

silverlight - Silverlight (v2) 中的 Sprite /角色动画

javascript - 退出时没有过渡或动画(smoothstate.js)

ruby-on-rails - "uninitialized constant"当包含测试助手模块时

ruby - 为什么模块的单例方法在混合的下游特征类中不可见?

dart - Flutter:TextFormField,更改文本

android - 在 Flutter 中以编程方式更改启动屏幕颜色

Flutter:关闭深色模式主题

android:如何动画翻译LayerDrawable的单层

ReactJS Reflux 在 ES6 中使用 mixin