我正在使用BLoC从Firestore加载我的预设对象。 这是我的Bloc模型:
class StatisticsBloc extends BlocBase {
List<Preset> _presets;
StreamController<List<Preset>> _presetsController = new StreamController();
Stream<List<Preset>> get getPresets => _presetsController.stream.asBroadcastStream();
StatisticsBloc() {
print('init Statistics Bloc');
_presets = [];
Firestore.instance.collection('Presets').snapshots().asBroadcastStream().listen(_onPresetsLoaded);
}
@override
void dispose() {
print('Disposed Statistics Bloc');
_presetsController.close();
}
void _onPresetsLoaded(QuerySnapshot data) {
_presets = [];
data.documents.forEach((DocumentSnapshot snap) {
Preset preset = Preset.fromDoc(snap);
_presets.add(preset);
});
_presetsController.sink.add(_presets);
}
}
然后我像这样显示列表:
class StatisticsPage extends StatelessWidget {
StatisticsPage() {
print('Created StatisticsPage');
}
@override
Widget build(BuildContext context) {
final StatisticsBloc statisticsBloc = BlocProvider.of<StatisticsBloc>(context);
final List<Preset> _ = [];
print(statisticsBloc.getPresets.isBroadcast);
return Scaffold(
appBar: AppBar(
title: Text('Statistics'),
),
body: StreamBuilder(
stream: statisticsBloc.getPresets,
initialData: _,
builder: (BuildContext context, AsyncSnapshot<List<Preset>> snapshot) {
if (snapshot.hasData) {
return ListView(
children: snapshot.data.map((Preset preset) {
print(preset.name);
return new ListTile(
title: new Text(preset.name),
subtitle: new Text(preset.id),
);
}).toList(),
);
} else {
Text('No Data');
print('No Data');
}
}
)
);
}
}
问题是,我在选项卡中显示StatisticsPage
,所以当我切换选项卡并返回它时,它将被构建多次。在第一次访问时它可以工作,但当我切换选项卡并返回时,小部件会重新构建并出现错误:Bad state: Stream has already been listened to.
。我尝试将getPresets
流声明为BroadcastStream,如您在StatisitcsBloc
中看到的,但这行不通。
另外,作为一个辅助问题:有没有更好的方法将我从Firestore获取的Stream<QuerySnapshot>
转换为Stream<List<Presets>>
?