ListView中的多个StreamBuilder无法收听同一个Stream

时间:2019-01-02 09:11:50

标签: dart flutter rxdart bloc

我在StreamBuilder中有2个ListView,他们在听同一个Stream,即valueStream。在该StreamBuilder中,我有SwitchListTilevalueStream添加了新值。

这是我的Stream

Observable<bool> get valueStream => valueController.stream;

这是我的ListView

ListView(
    children: <Widget>[
        Switch1(key: UniqueKey(),),
        Switch2(key: UniqueKey(),),
    ],
),

这是Switch1小部件:

class Switch1 extends StatefulWidget {
  const Switch1(
      {@required Key key})
      : super(key: key);

  @override
  _Switch1State createState() => _Switch1State();
}

class _Switch1State extends State<Switch1> {
  DummyBloc _dummyBloc;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      key: UniqueKey(),
      stream: _dummyBloc.valueStream,
      builder: (context, AsyncSnapshot<bool> snapshot) {
        print('rebuild Switch1');
        if(!snapshot.hasData) return Container();
        return SwitchListTile(
          value: snapshot.data,
          onChanged: _dummyBloc.updateValue,
        );
      },
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _dummyBloc = DummyBloc();
  }
}

这是Switch2小部件:

class Switch2 extends StatefulWidget {
  const Switch2(
      {@required Key key})
      : super(key: key);

  @override
  _Switch2State createState() => _Switch2State();
}

class _Switch2State extends State<Switch2> {
  DummyBloc _dummyBloc;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      key: UniqueKey(),
      stream: _dummyBloc.valueStream,
      builder: (context, AsyncSnapshot<bool> snapshot) {
        print('rebuild Switch2');
        if(!snapshot.hasData) return Container();
        return SwitchListTile(
          activeColor: Theme.of(context).buttonColor,
          value: snapshot.data,
          onChanged: _dummyBloc.updateValue,
        );
      },
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _dummyBloc = DummyBloc();
  }
}

如果我触摸Switch1小部件,则StreamBuilder内部的Switch2可能会重建,反之亦然,但这没有发生。我试图将UniqueKey添加到Switch1Switch2中,但这无济于事。任何建议如何使这项工作?

0 个答案:

没有答案