Sco*_*ran 2 animation mixins flutter 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>'.
Run Code Online (Sandbox Code Playgroud)
这是我的代码
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();
}
}
Run Code Online (Sandbox Code Playgroud)
因为要初始化 AnimationController,它需要一个名为“vsync”的参数,所以我必须实现 mixin SingleTickerProviderStateMixin。但是因为 GetView<> 没有实现 State 所以它会抛出编译错误。
我不知道在 GetX 中实现动画的正确方法是什么,奇怪的是我无法在 Google 或任何 flutter 社区上找到任何线索或指南,尽管 GetX 广泛流行
您想在控制器类上使用with GetSingleTickerProviderStateMixin,而不是在实际页面上使用。这是特定于 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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在扩展的页面中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();
}
}
Run Code Online (Sandbox Code Playgroud)
只需确保HomePageController在加载主页之前已完全初始化即可。如果HomePage这是应用程序中的第一件事,那么保证其在HomePage尝试加载之前初始化的一种方法是使用FutureGetX 类中的方法初始化控制器。
Future<void> initAnimationController() async {
animationController = AnimationController(vsync: this, duration: duration);
}
Run Code Online (Sandbox Code Playgroud)
然后在 main 方法中进行初始化。
void main() async {
final controller = Get.put(HomePageController());
await controller.initAnimationController();
runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)
根据我的经验,如果您在应用程序加载的第一页中使用 Getx 类中的动画控制器,则在 中进行初始化并onInit不能保证它已准备就绪,并且可能会引发错误。在 main 中使用Future方法 andawait将确保您不会收到未初始化的错误。