如何在 GetX 中使用 AnimationController 而不是使用 StatefulWidget 和 SingleTickerProviderStateMixin

Mah*_*oon 10 dart flutter

我有一个initState()方法,包含AnimationController以下代码:

_controller = AnimationController(
      vsync: this,
      duration: const Duration(
        milliseconds: 2500,
      ),
    );
Run Code Online (Sandbox Code Playgroud)

例如我想使用以下方式:

import 'package:get/get.dart';
import 'package:flutter/material.dart';

class ControllerViewModel extends GetxController {
  AnimationController _controller;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(
        milliseconds: 2500,
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但当然我发现了一个错误The argument type 'ControllerViewModel' can't be assigned to the parameter type 'TickerProvider'.

AnimationController那么有没有办法在 GetX 状态管理方式中使用它呢?

Mah*_*oon 19

我找到了一个解决方案,只需添加 即可GetSingleTickerProviderStateMixin 成为完整代码,如下所示:

import 'package:get/get.dart';
import 'package:flutter/material.dart';

class ControllerViewModel extends GetxController with GetSingleTickerProviderStateMixin {
  AnimationController _controller;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(
        milliseconds: 2500,
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 将 SingleGetTickerProviderMixin 更新为 GetSingleTickerProviderStateMixin,因为“SingleGetTickerProviderMixin”已弃用且不应使用。使用 GetSingleTickerProviderStateMixin。尝试用替换成员替换已弃用成员的使用 (2认同)