DolDurma
DolDurma

Reputation: 17380

Flutter manage animation controller from outside of class

this is my simple animation in class witch i use that

controller = AnimationController(vsync: this, duration: Duration(milliseconds: 200));

offset = Tween<Offset>(begin: Offset.zero, end: Offset(0.0, -1.0)).animate(controller);
controller.forward();

in that i can only manage animation controller such as forward, reverse inside of class and i try to move this controller to outside of class like with another class as NotificationBarController, is any body help me how can i achieve to this solution?

for example

controller = NotificationBarController();
controller.forward();

source code

class NotificationBar extends StatefulWidget {
  final Widget contentWidget;
  final Widget barWidget;

  NotificationBar({@required this.contentWidget, @required this.barWidget});

  @override
  State<StatefulWidget> createState() => NotificationBarState();
}

class NotificationBarState extends State<NotificationBar>  with SingleTickerProviderStateMixin {
  AnimationController controller;
  Animation<Offset> offset;

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

    controller = AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    // offset = Tween<Offset>(begin: Offset.zero, end: Offset(1.0, 0.0)).animate(controller); from right
    offset = Tween<Offset>(begin: Offset.zero, end: Offset(0.0, -1.0)).animate(controller);
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
      ),
    );
  }
}

my tired class to implementing that, but this is wrong

class NotificationBarController  extends ChangeNotifier {
  NotificationBarController({@required TickerProvider vsync}): _animationController = AnimationController(vsync: vsync);

  Animation<double> get animation => _animationController?.view ?? kAlwaysCompleteAnimation;

  Animation<double> get state => _animationController?.view ?? kAlwaysCompleteAnimation;

}

Upvotes: 5

Views: 2501

Answers (1)

Mikhail Ponkin
Mikhail Ponkin

Reputation: 2711

You can use GlobalKey for it. First you need to instantiate and store it like this final key = GlobalKey<NotificationBarState>(), then you need to pass it to NotificationBar constructor calling super with the key. Then you can access the state and its members by calling key.currentState.someMethod().

However the whole idea doesn't look like Flutter way for me. I would suggest to subscribe to some stream or changeNotifier inside NotificationBarState and fire animation as a reaction on new event or notification

Upvotes: 4

Related Questions