'Bloc returns an empty array, but renders a lot of widgets
I'm trying to use BLoC as a state management in my application, and I encountered two problems I can't seem to fix. First, I always get a null value instead of the data. Second, although I get null value, the component still renders a lot of widgets.
This is my component:
StreamBuilder<List<CustomItem>>(
stream: _itemsBloc.itemsStream,
builder: ((context, snapshot) {
final items = snapshot.data;
return Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: items?.length,
itemBuilder: (BuildContext context, int index) {
var i = items?[index];
return CustomItem(
name: e != null ? e.name : "",
color: e != null ? e.color : "",
);
}),
);
}),
),
This is my BLoC class:
enum ItemsEvent {
fetch,
}
class ItemsBloc {
final _eventController = StreamController<ItemsEvent>();
Stream<ItemsEvent> get eventStream => _eventController.stream;
Sink<ItemsEvent> get eventSink => _eventController.sink;
final _itemsController = StreamController<List<CustomItem>>();
Stream<List<CustomItem>> get itemsStream =>
_itemsController.stream;
Sink<List<CustomItem>> get itemsSink => _itemsController.sink;
List<CustomItem> items = [];
ItemsBloc() {
eventStream.listen((ItemsEvent event) async {
switch (event) {
case ItemsEvent.fetch:
items = await DataService.fetchItems();
break;
default:
}
});
}
}
This is how I try to fetch the data from the component:
@override
void initState() {
super.initState();
_itemsBloc.eventSink.add(ItemsEvent.fetch);
}
What is wrong here, and why the widgets still render although no data is provided?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
