我想使用一个带有BottomNavigationBar的StatelessWidget,并从BLOC控制它。我可以将Scaffold的body和BottomNavigationBar的onTap与BLOC连接起来(请参见代码)。但是我不知道如何从BLOC(从Observable)设置BottomNavigationBar的currentIndex。
是否有好的解决方案,或者我需要像https://dev59.com/KK_la4cB1Zd3GeqPsGSX#53019841中一样使用StatefulWidget,这与我的示例类似。
BLOC代码:
小部件代码:
是否有好的解决方案,或者我需要像https://dev59.com/KK_la4cB1Zd3GeqPsGSX#53019841中一样使用StatefulWidget,这与我的示例类似。
BLOC代码:
class Bloc {
final _currentTabSink = PublishSubject<int>();
final _currentTabIndex = BehaviorSubject<int>();
Observable<int> get currentTabIndex => _currentTabIndex.stream;
Function(int) get setTabIndex => _currentTabSink.sink.add;
Bloc() {
_currentTabSink.stream.pipe(_currentTabIndex);
}
dispose() {
_currentTabSink.close();
_currentTabIndex.close();
}
}
小部件代码:
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final bloc = Provider.of(context);
final List<Widget> _children = [
AaWidget(),
BbWidget(),
CcWidget(),
DdWidget(),
EeWidget()
];
return Scaffold(
appBar: AppBar(
title: Text(Localizations.of(context).appName),
),
body: setBody(_children, bloc), // hook to BLOC
bottomNavigationBar: BottomNavigationBar(
currentIndex: 1, // ?? how to hook up to BLOC ??
onTap: (index) {
bloc.setTabIndex(index); // hook to BLOC
},
items: [
addAa(context),
addBb(context),
addCc(context),
addDd(context),
addEE(context),
],
));
}
Widget setBody(List<Widget> children, Bloc bloc) {
return StreamBuilder(
stream: bloc.currentTabIndex,
builder: (context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData) {
return children[snapshot.data];
}
},
);
}
...
}