【问题标题】:flutter how to implement animation inside class GetView<Controller>颤动如何在类 GetView<Controller> 中实现动画
【发布时间】:2021-07-25 00:38:46
【问题描述】:

我正在做一个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 中实现动画的正确方法是什么,奇怪的是,尽管 GetX 广受欢迎,但我在 Google 或任何 Flutter 社区都找不到任何线索或指南

【问题讨论】:

  • Getx 现在支持GetTickerProviderStateMixin

标签: flutter animation mixins flutter-getx


【解决方案1】:

尝试使用 GetX 版本的 SingleTickerProviderStateMixin - SingleGetTickerProviderMixin

class HomePage extends GetView<HomePageController> with SingleGetTickerProviderMixin {

}

【讨论】:

  • 感谢关键字 SingleGetTickerProviderMixin,这正是我所需要的。但是如果在 HomePage 上实现它,它也会抛出编译错误,说 GetView 没有实现'DisposableInterface'。 Loren.A 的答案更正确,在 Controller 类中实现混合
【解决方案2】:

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

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

  AnimationController animationController;

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

然后在扩展GetView&lt;HomePageController&gt; 的页面中使用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 方法初始化控制器。

 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 类中的动画控制器,则在 onInit 中进行初始化并不能保证它已经准备好并且可能会引发错误。在 main 中使用 Future 方法和 await 将确保您不会收到未初始化的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2021-07-15
    • 2019-01-04
    相关资源
    最近更新 更多