用Flutter BottomNavigationBar重建相同的选项卡

问题描述

我对Flutter BottomNavigationBar有问题。我用3个项目构建了一个BottomNavigationBar,完整的代码

class TabPage extends StatefulWidget {
  @override
  _TabPageState createState() => _TabPageState();
}

class _TabPageState extends State<TabPage> {
  int _currentIndex = 0;

  final Map<int,Widget> _routes = <int,Widget>{
    0: MainTab(),1: NotificationTab(),2: BlocProvider(
      create: (context) => ProfileBloc(DataProvider()),child: ProfileTab(),),};

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        showUnselectedLabels: false,currentIndex: _currentIndex,type: BottomNavigationBarType.fixed,onTap: _onTabTapped,items: [
          BottomNavigationBarItem(
            icon: Icon(
              Icons.language,label: AppLocalizations.of(context).translate("home"),BottomNavigationBarItem(
            icon: Icon(
              Icons.notifications,label: AppLocalizations.of(context).translate("notification"),BottomNavigationBarItem(
            icon: Icon(
              Icons.person,label: AppLocalizations.of(context).translate("profile"),)
        ],body: _routes[_currentIndex],);
  }
}

如果我从一个选项卡切换到另一个选项,一切都可以正常工作,问题是如果用户点击当前选定的选项卡,则该选项卡不会失效。第一个选项卡是带有WebView的小部件,因此即使用户已经在该选项卡上,我也希望用户返回initialUrl。似乎点击当前选择的选项卡无效。有没有办法重建后代小部件?

class MainTab extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: WebView(
        initialUrl: "https://www.google.com/",javascriptMode: JavascriptMode.unrestricted,);
  }
}

解决方法


  final Map<int,Widget> _routes = <int,Widget>{
    0: MainTab(key : UniqueKey()),// add key to every widget and pass it to super constructor.
    1: NotificationTab(key : UniqueKey()),2: BlocProvider(
      create: (context) => ProfileBloc(DataProvider()),child: ProfileTab(key : UniqueKey()),),};