Rebuild same tab with Flutter BottomNavigationBar

209 views Asked by At

i have a problem with Flutter BottomNavigationBar. i built a BottomNavigationBar with 3 items, the complete code is

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],
    );
  }
}

Everything works fine if i switch from a tab to another, the problem is that the tab is not relodead if the user tap on the currently selected tab. The first tab is a widget with a WebView so i want the user returns to initialUrl even if he is already on that tab. It seems that tapping on the currently selected tab has no effect. Is there a way to rebuild the descendent widget?

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

There are 1 answers

0
UTKARSH Sharma On

  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()),
    ),
  };