AnimationController:我们可以将 TickerProvider vsync 传递给其他类吗?

Lab*_*Lab 4 animation ticker flutter

我在 Flutter 中开发了一个应用程序,其中有很多不同的动画。我想通过分离视图、逻辑(模型 BLoC)和动画来构建我的代码。对于这个问题,我尝试为 StatefulWidget 的不同类中的按钮声明多次相同的动画。

但是,我陷入困境,因为我必须将 TickerProvider 传递给我的动画类,而我没有以正确的方式执行此操作。

构造函数动画类

AppBloc(TickerProvider tickerProvider) {
    banimationController = AnimationController(
      vsync: tickerProvider,
      duration: Duration(milliseconds: 100),
      lowerBound: 0,
      upperBound: 0.05,
    );
}
Run Code Online (Sandbox Code Playgroud)

宣言

AppBloc(this);
Run Code Online (Sandbox Code Playgroud)

我知道这可能不是正确的方法,我编写了这段代码来说明我的问题。

我只想将我的动画声明分离到另一个文件中。

小智 5

TickerProvider是一个 mixin。您可以使用with关键字在一个类中使用多个 mixin。使用 mixin uff TickerProvider 的最佳方法是将其与with关键字一起使用。

例子 :

  class _HomeState extends State<Home> with TickerProviderStateMixin {
  Animation<double> _animation;
  AnimationController _animationController;

  GoogleSignIn _googleSignIn;
  GoogleSignInAccount _googleSignInAccount;
  GoogleSignInAuthentication _googleSignInAuthentication;
  FirebaseAuth _auth;

 // FacebookLoginResult _facebookLoginResult;
  // FacebookLogin _facebookLogin;
   // FirebaseUser facebookUser;

  @override
  void initState() {
    super.initState();
    _animationController =
        AnimationController(vsync: this, duration: Duration(seconds: 4));
    _animation = Tween<double>(begin: -1.0, end: 0.0).animate(CurvedAnimation(
        parent: _animationController, curve: Curves.fastOutSlowIn));

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

 @override
  Widget build(BuildContext context) {
return widget();
}
}
Run Code Online (Sandbox Code Playgroud)

如果您以这种方式使用 TickelProvider,那么您只需将作为 vsync 的值传递即可。

  • `TickerProvider` 不是一个 mixin。它是 `TickerProviderStateMixin` 实现的接口。因此,这个 mixin 是一个 `TickerProvider`,但反之则不然。 (2认同)