Search code examples
flutterdartflutter-animation

Flutter: AnimationController vsync this issue


I am trying to implement code from official docs example but it fails:

...

class _MyHomePageState extends State<MyHomePage> {

  late AnimationController controller;

  @override
  void initState() {
    super.initState();

    controller = AnimationController(duration: Duration(seconds: 3), vsync: this);
  }

...

enter image description here

It says that: The argument type '_MyHomePageState' can't be assigned to the parameter type 'TickerProvider'.

So, VSCode highlights vsync: this param.

I have latest version of Flutter:

Flutter 2.5.3 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 18116933e7 (6 weeks ago) • 2021-10-15 10:46:35 -0700
Engine • revision d3ea636dc5
Tools • Dart 2.14.4

Why this error occurs and how to fix this without downgrading of SDK version?


Solution

  • In Flutter, an AnimationController needs a TickerProvider.

    When an AnimationController is being created from a State, you should have the State to extend either TickerProviderStateMixin or SingleTickerProviderStateMixin. The latter is more optimized for when you only need to use a single ticker, which should be most of the case.

    Solution for you:

    Change

    class _MyHomePageState extends State<MyHomePage>
    

    into

    class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin