How do I use a Instance in an Initializer

I cannot pass the controller or the offsetAnimation instances to Initialize SideBar()

SideBarWidget class

class SideBarWidget extends StatelessWidget {
  SideBarWidget({Key? key, required this.controller}) : super(key: key);

  final AnimationController controller;
  final Animation<Offset> offsetAnimation = Tween<Offset>(...).animate(...);

  final sideBar = SideBar(
    itemList: [...],
    controller: controller , //_The instance member 'controller' can't be accessed in an initializer_
    offsetAnimation: offsetAnimation ,//_The instance member 'offsetAnimation' can't be accessed in an initializer_
  );

  void toggle() {...}

  @override
  Widget build(BuildContext context) {...}
}


I also cannot use the this. method. How can I solve this…

Thank You

>Solution :

The error message you’re seeing is indicating that the controller and offsetAnimation variables are instance variables and cannot be accessed in the initializer of the sideBar variable.

class SideBarWidget extends StatelessWidget {
  SideBarWidget({Key? key, required this.controller}) : super(key: key);

  final AnimationController controller;
  final Animation<Offset> offsetAnimation = Tween<Offset>    (...).animate(...);

  void toggle() {...}

  @override
  Widget build(BuildContext context) {
    final sideBar = SideBar(
      itemList: [...],
      controller: controller,
      offsetAnimation: offsetAnimation,
    );

    return sideBar;
  }
}

This way, when the "build" method is called, the "controller" and "offsetAnimation" variables have already been initialized and can be passed as arguments to the "SideBar" constructor.

Leave a Reply