title: flutter navigate back to selected page
body: <p>I have a application with contains a bottom navigation that when the app loads it defaults to the first page. If I were to click onto the second page and then from the second page, I navigate to another separate page that is not linked to the bottom navigation bar. When I click the back button in the Appbar in this page, I am take to page one again instead of page 2. </p>
  
  <p><strong>Navigation Controller:</strong></p>
  
  <pre><code>import 'package:flutter/material.dart';
  import '../pages/TaxCalcPage.dart';
  import '../pages/TaxInfoPage.dart';
  import '../pages/SettingsPage.dart';
  
  class BottomNavigationBarController extends StatefulWidget {
    @override
    _BottomNavigationBarControllerState createState() =&gt;
        _BottomNavigationBarControllerState();
  }
  
  class _BottomNavigationBarControllerState extends State&lt;BottomNavigationBarController&gt; {
    final List&lt;Widget&gt; pages = [
      TaxCalcPage(
        key: PageStorageKey('Page1'),
      ),
      TaxInfoPage(
        key: PageStorageKey('Page2'),
      ),
      SettingsPage(
        key: PageStorageKey('Page3'),
      )
    ];
  
    final PageStorageBucket bucket = PageStorageBucket();
  
    int _selectedIndex = 0;
  
    Widget _bottomNavigationBar(int selectedIndex) =&gt; BottomNavigationBar(
          onTap: (int index) =&gt; setState(() =&gt; _selectedIndex = index),
          currentIndex: selectedIndex,
          items: const &lt;BottomNavigationBarItem&gt;[
            BottomNavigationBarItem(
                icon: Icon(Icons.home), title: Text('Tax Calculators')),
            BottomNavigationBarItem(
                icon: Icon(Icons.info), title: Text('Tax Information')),
            BottomNavigationBarItem(
                icon: Icon(Icons.settings), title: Text('Settings')),
          ],
        );
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
        body: PageStorage(
          child: pages[_selectedIndex],
          bucket: bucket,
        ),
      );
    }
  }
  </code></pre>
  
  <p><strong>Page:</strong></p>
  
  <pre><code>return Scaffold(
      appBar: AppBar(
        leading: Builder(
        builder: (BuildContext context) {
          return IconButton(
            icon: const Icon(Icons.chevron_left),
            iconSize: (0.06 * ratio) * width,
            splashColor: Colors.transparent,  
            highlightColor: Colors.transparent,
            onPressed: () =&gt; Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) =&gt; BottomNavigationBarController()), (Route route) =&gt; route == null),
          );
        },
      ),
  </code></pre>
  
  <p>So when I navigate back using the icon in the AppBar. I will take me to page 1 instead of Page 2</p>