我正在创建TabBarView,并且该视图的子级是使用BLoC模式创建的。当我在BLoC中使用基本流时,我的标签页中得到空结果。但是,当我将流切换为BehaviorSubject时,会收到预期的结果-带有列表的页面。为什么基本的Dart Streams无法同时工作?
(我正在使用Kiwi依赖注入-工作正常,没有提供的值为空)
BLoC类(Stream被BehaviorSubject替换)
class EventsListBloc implements BlocBase{
Repository _repo;
StreamSubscription _agendaSub;
BehaviorSubject<List<Event>> _subject;
StreamController<List<Event>> _eventController = StreamController<List<Event>>.broadcast();
Sink<List<Event>> get _eventsInput => _eventController.sink;
Stream<List<Event>> get eventsStream => _subject.stream;//_eventController.stream;
EventsListBloc(){
_repo = getContainer()<Repository>();
_subject = BehaviorSubject();
_agendaSub = _repo.eventsList.listen(_updateAgenda);
}
_updateAgenda(List<Event> eventsList){
//_eventsInput.add(eventsList);
_subject.value = eventsList;
}
void dispose() {
print("EventsListBloc: disposing");
_eventController.close();
_agendaSub.cancel();
_subject.close();
}
}
TabBarView容器:
class AgendaPage extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _AgendaPageState();
}
}
class _AgendaPageState extends State<AgendaPage>{
Widget _provideListView(){
return BlocProvider(
bloc: EventsListBloc(),
child: AgendaListWidget()
);
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: Center(
child: Text('Agenda')
),
bottom: TabBar(
tabs: <Widget>[
Tab(
text: "test 1",
),
Tab(
text: "test 2",
)
],
)//tabsy,
),
body: TabBarView(
children: [_provideListView(), _provideListView()]
),
),
);
}
}
标签页(正在使用BLoC的ListView)
class AgendaListWidget extends StatefulWidget{
@override
_AgendaListWidgetState createState() {
return new _AgendaListWidgetState();
}
}
class _AgendaListWidgetState extends State<AgendaListWidget> {
Widget _buildItem(BuildContext context, Event event){
var item = Card(
child: Text(event.title),
);
return item;
}
Widget _buildList(BuildContext context){
final eventsBloc = BlocProvider.of<EventsListBloc>(context);
assert(eventsBloc != null);
var result = StreamBuilder<List<Event>>(
stream: eventsBloc.eventsStream,
builder: (BuildContext context, AsyncSnapshot<List<Event>> snapshot) {
if(snapshot.hasData){
var result = ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) =>
_buildItem(context, snapshot.data[index])
,
);
return result;
}else{
return const Text("Empty");
}
},
);
return result;
}
@override
Widget build(BuildContext context) {
return _buildList(context);
}
}
BehaviorSubject的结果:
流的结果: