Flutter - BLoC 模式 - 如何使用流调用另一个小部件的方法,即动画?

Flutter - BLoC pattern - How to use streams to invoke a method of another widget, i.e. an animation?

假设有一个小部件具有控制可见性动画的方法,toggleVisibility()。在 BLoC 模式中,我想使用流来调用该函数。我觉得这很棘手。

  1. 由于它是动画而不是完全重绘,因此不适合使用 StreamBuilder。
  2. 手动向 BLoC 流添加监听器也不方便。

    1. 在目标小部件的 initeState() 函数中,我们没有上下文,因此很难获得对 BLoC 的引用。

    编辑:我阅读后情况并非如此。我们甚至可以在 build() 函数之外访问上下文,因为 State<T> class 有一个名为 'context' 的 属性 并且记录在 Flutter 的文档中....我没有意识到这一点。

    1. 在目标小部件的 build(context) 函数中,我们有上下文。但是小部件可以经常重新构建,因此您必须手动清理过时的订阅。否则会产生成吨的垃圾。
  3. StreamBuilder 可以破解,因为 StreamBuilder 已经实现了所有的订阅和取消订阅功能。在目标小部件的布局中的某处插入一个 StreamBuilder。
StreamBuilder(
    stream: Bloc.of(context).stream,
    builder: (context, snapshot){
        toggleVisiblity();
        return Container():
    }
);

但这确实是一个 hack。它将布局与逻辑混合在一起,并引入了一个可能导致布局错误的无用小部件。

所以想知道在flutter中有没有什么好的方法可以做到这一点

您不能使用 StreamBuilder 来做到这一点。您必须手动收听流

class Example extends StatefulWidget {
  @override
  ExampleState createState() => ExampleState();
}

class ExampleState extends State<Example> {
  StreamSubscription subscription;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    Stream stream = Bloc.of(context).someStream;
    subscription?.cancel();
    subscription = stream.listen((value) {
      // do something
    });
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}