Nested Navigation in Flutter: ListView not replaced when navigating within Navigator

18 views Asked by At

I am facing an issue with Flutter navigation (tested on Android 33 API experimental and Linux) when using a ListView within a nested navigation structure, where the BottomNavigationBar and the Navigator widget, sharing the same key, are placed on the same level. Here is the simplified widget hierarchy:

Scaffold
|-- Navigator
|   |-- Screen A
|   |   |-- ListView
|   |
|   |-- Screen B
|       |-- Other content
|
|-- BottomNavigationBar
    |-- BottomNavItem 1
    |-- BottomNavItem 2

The problem occurs when navigating from items within the ListView on Screen A. The ListView remains visible, and the new content is not replacing it.

Here is a slightly simplified code snipped inspired by the flutter tutorial on nested navigation:

    return PopScope(
      canPop: false,
      onPopInvoked: ...,
      child: Scaffold(
        body: Navigator(
          key: navigatorKey,
          onGenerateRoute: RouteGenerator().generateRoute,
          initialRoute: "/home",
        ),
        bottomNavigationBar: AppBottomBarTabSelector(
          activeTab: _selectedTab,
          onTabSelected: (tab) {
            navigatorKey.currentState!.pushNamed('/${tab.name}');
            // setState(() {
            //   if (_selectedTab != tab) {
            //     _selectedTab = tab;
            //   }
            // });
          },
        ),
      ),
    );

And here is the content of the error causing PageRoute, which is essentially a randomly generated 100 elements ListView:

    return SizedBox(
      height: 800,
      width: 400,
      child: ListView.builder(
        itemCount: items.length,
        prototypeItem: ListTile(
          title: Text(items.first),
        ),
        itemBuilder: (context, index) {
          return ListTile(
            tileColor:
                Colors.primaries[Random().nextInt(Colors.primaries.length)],
            title: Text(items[index]),
          );
        },
      ),
    );

However, when I wrap the ListView with a Scaffold, the navigation works as intended:

Scaffold
|-- Navigator
|   |-- Screen A
|   |   |-- Scaffold
|   |       |-- ListView
|   |
|   |-- Screen B
|       |-- Other content
|
|-- BottomNavigationBar
    |-- BottomNavItem 1
    |-- BottomNavItem 2

Methods to ensure the widget is deactivated correctly were using the Scaffold wrapping, which is not recommended in the official description page of the Scaffold widget or simply utilizing methods to clear the navigation stack, forcing a dispose instead of a deactivate.

However, this still seems like unwanted behaviour. Is there a known issue with using a ListView within a nested navigation environment? Can this be fixed without removing the stack or nesting Scaffold widgets ?

0

There are 0 answers