My ApplicationBloc is the root of the widget tree. In the bloc's constructor I'm listening to a stream from a repository that contains models decoded from JSON and forwarding them to another stream which is listened to by StreamBuilder.
I expected that StreamBuilder would receive models one by one and add them to AnimatedList. But there's the problem: StreamBuilder's builder fires only once with the last item in the stream.
For example, several models lay in the local storage with ids 0, 1, 2 and 3. All of these are emitted from repository, all of these are successfully put in the stream controller, but only the last model (with id == 3) appears in the AnimatedList.
Repository:
class Repository {
static Stream<Model> load() async* {
//...
for (var model in models) {
yield Model.fromJson(model);
}
}
}
Bloc:
class ApplicationBloc {
ReplaySubject<Model> _outModelsController = ReplaySubject<Model>();
Stream<Model> get outModels => _outModelsController.stream;
ApplicationBloc() {
TimersRepository.load().listen((model) => _outModelsController.add(model));
}
}
main.dart:
void main() {
runApp(
BlocProvider<ApplicationBloc>(
bloc: ApplicationBloc(),
child: MyApp(),
),
);
}
//...
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
final ApplicationBloc appBloc = //...
return MaterialApp(
//...
body: StreamBuilder(
stream: appBloc.outModels,
builder: (context, snapshot) {
if (snapshot.hasData) {
var model = snapshot.data;
/* inserting model to the AnimatedList */
}
return AnimatedList(/* ... */);
},
),
);
}
}
Interesting notice: in the StreamBuilder's _subscribe() method onData() callback triggers required number of times but build() method fires only once.