【问题标题】:Flutter manage animation controller from outside of classFlutter 从课外管理动画控制器
【发布时间】:2019-11-17 07:46:43
【问题描述】:

这是我在课堂上使用的简单动画

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

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

因为我只能在课堂内管理动画控制器,例如 forwardreverse,我尝试将此控制器移动到课堂外,就像另一个课堂 NotificationBarController 一样,是否有任何机构可以帮助我我实现了这个解决方案?

例如

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

源代码

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(
      ),
    );
  }
}

我厌倦了实现它,但这是错误的

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;

}

【问题讨论】:

    标签: flutter flutter-animation


    【解决方案1】:

    您可以使用 GlobalKey。 首先,您需要像这样实例化和存储它 final key = GlobalKey&lt;NotificationBarState&gt;(),那么您需要将其传递给NotificationBar 构造函数,并使用密钥调用super。然后你可以通过调用key.currentState.someMethod()来访问状态和它的成员。

    然而,整个想法对我来说并不像 Flutter 方式。我建议订阅 NotificationBarState 中的一些流或 changeNotifier 并触发动画作为对新事件或通知的反应

    【讨论】:

    • 我需要实现代码才能知道如何做到这一点
    • 检查here
    • 谢谢,我想这不是我想要的。请将此库视为分离类上的动画控制器github.com/mcrovero/rubber
    • 这与原来的问题相差甚远
    • 我很抱歉这个错误
    猜你喜欢
    • 2018-10-21
    • 2021-09-07
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2021-04-09
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多