问题描述
我正在启动一个 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 很受欢迎
解决方法
尝试使用 SingleTickerProviderStateMixin
- SingleGetTickerProviderMixin
的 GetX 版本:
class HomePage extends GetView<HomePageController> with SingleGetTickerProviderMixin {
}
,
您想在控制器类上使用 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<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
方法初始化控制器。
Future<void> initAnimationController() async {
animationController = AnimationController(vsync: this,duration: duration);
}
然后在你的主方法中初始化。
void main() async {
final controller = Get.put(HomePageController());
await controller.initAnimationController();
runApp(MyApp());
}
根据我的经验,如果您在应用加载的第一页中使用 Getx 类中的动画控制器,则在 onInit
中初始化并不能保证它会准备好并可能引发错误.在 main 中使用 Future
方法和 await
将确保您不会收到未初始化的错误。