[英]flutter how to implement animation inside class GetView<Controller>
我正在啟動一個 flutter 項目,很多人說 GetX 是在 flutter 中使用的最好的 state 管理器框架,所以我決定使用它。
我想在 class 主頁中做一些 animation,但是當我使用 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 中實現 animation 的正確方法是什么,奇怪的是我在 Google 或任何 flutter 社區上找不到任何線索或指南,盡管 GetX 廣受歡迎
您想在with GetSingleTickerProviderStateMixin
上使用 GetSingleTickerProviderStateMixin,而不是您的實際頁面。 這是 GetX 特有的,允許您在無狀態小部件上使用 animation 控制器。
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>
的頁面中訪問 animation controller 和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
是您的應用程序中的第一件事,那么保證在HomePage
嘗試加載之前對其進行初始化的一種方法是使用 GetX class 中的Future
方法初始化 controller。
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
controller,則在 onInit 中初始化並可能會引發錯誤。 使用Future
方法並在 main 中await
將確保您不會收到未初始化的錯誤。
嘗試使用 GetX 版本的SingleTickerProviderStateMixin
- SingleGetTickerProviderMixin
:
class HomePage extends GetView<HomePageController> with SingleGetTickerProviderMixin {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.