我在无状态小部件中有一个 BottomNavigationBar。我正在使用 ViewModelProvider 来控制 onTap 事件时的选项卡更改。使用 BottomNavigationBar 导航没有问题,但我无法从正文内部控制导航栏。我正在使用以下方法,我尝试使用 streambuilder 来控制导航,但是当导航到另一个我不想要的选项卡时,streambuilder 会处理内容。我无法单击个人资料页面中的按钮并导航到主页。
下面是我的 BottomNavigationBar 小部件。
class BottomNavigationView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ViewModelProvider<BottomNavigationViewModel>.withConsumer(
viewModel: BottomNavigationViewModel(),
builder: (context, model, child) => Scaffold(
primary: false,
body: IndexedStack(
children: <Widget>[
BrowseView(),
HomeView(),
ProfileView(),
],
index: model.currentIndex,
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.white,
currentIndex: model.currentIndex,
onTap: model.changeView,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.search),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: SizedBox.shrink(),
),
BottomNavigationBarItem(
icon: new Icon(WineIcon.person),
title: SizedBox.shrink(),
),
],
),
),
);
}
}
导航栏视图模型
class BottomNavigationViewModel extends ChangeNotifier {
int _currentIndex = 2;
int get currentIndex => _currentIndex;
void changeView(int index) {
_currentIndex = index;
notifyListeners();
}
}
纵断面图和纵断面图模型
class ProfileView extends StatelessWidget {
const ProfileView ({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ViewModelProvider<ProfileViewModel>.withConsumer(
viewModel: ProfileViewModel(),
builder: (context, model, child) => Scaffold(
body: Center(
child: RaisedButton(
onPressed: ()=> model.goHome(),
child:Text('Go to Home'),
),
)
),
);
}
}
class ProfileViewModel extends ChangeNotifier {
final BottomNavigationViewModel _bottomNavigationBar =
locator<BottomNavigationViewModel>();
void goHome() {
_bottomNavigationBar.changeView(1);
}
}