when I rebuild a widget which is an ancestor of another widget that contains StreamBuilder
class, the last one is loading forever.
I am posting a simple example:
This build method is the Ancestor widget, a stateful
widget.
The _buildForm
method contains the Widget with the StreamBuilder
.
@override
Widget build(BuildContext context) {
if (_isSaving) {
return FutureBuilder<void>(
future: _saveData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
_isSaving = false;
if (snapshot.hasError) {
Future.delayed(Duration.zero, () async {
ScaffoldMessenger.of(context).showSnackBar(
_notice("error: ${snapshot.error.toString()}"));
});
} else {
Future.delayed(Duration.zero, () async {
ScaffoldMessenger.of(context).showSnackBar(
_notice("OK!"));
});
}
return _buildForm(context);
}
});
} else {
return _buildForm(context);
}
}
}
This is the descendant widget,a stateful
widget, with the StreamBuilder
widget:
final Stream<List<ProductType>> _streamProductTypes = (() async* {
await for (var e in EntityControllers.productTypeController.readStream()) {
yield e.cast<ProductType>();
}
})();
StreamBuilder<List<ProductType>>(
stream: _streamProductTypes,
builder: (BuildContext context,
AsyncSnapshot<List<ProductType>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return Text(snapshot.data!);
});
Every time I rebuild the ancestor Widget the StreamBuilder
widget is loading forever.
What's wrong with that?
Update
I have changed the _streamProductTypes with this function:
Stream<List<Entity>> readStream() {
return
FirebaseFirestore.instance.collection(entityName).withConverter<Entity>(fromFirestore: (snapshot, _) => fromConstructor(snapshot.data()!),
toFirestore: (entity, _) => entity.toJson(),
)
.snapshots()
.map((event) => event.docs.map((e) => e.data()).toList());
}
When I click to go to a new screen then I go again to that stream screen, there are no more data. Why?