我在StreamBuilder
中有2个ListView
,他们在听同一个Stream
,即valueStream
。在该StreamBuilder
中,我有SwitchListTile
为valueStream
添加了新值。
这是我的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
添加到Switch1
和Switch2
中,但这无济于事。任何建议如何使这项工作?