飘动导航回到所选页面

时间:2019-08-05 15:57:57

标签: flutter

我有一个应用程序,其中包含一个底部导航,该导航在应用程序加载时默认为第一页。如果要单击第二个页面,然后从第二个页面,请导航到另一个未链接至底部导航栏的单独页面。当我单击此页面上的应用栏中的后退按钮时,我将转到第一页而不是第二页。

导航控制器:

import 'package:flutter/material.dart';
import '../pages/TaxCalcPage.dart';
import '../pages/TaxInfoPage.dart';
import '../pages/SettingsPage.dart';

class BottomNavigationBarController extends StatefulWidget {
  @override
  _BottomNavigationBarControllerState createState() =>
      _BottomNavigationBarControllerState();
}

class _BottomNavigationBarControllerState extends State<BottomNavigationBarController> {
  final List<Widget> pages = [
    TaxCalcPage(
      key: PageStorageKey('Page1'),
    ),
    TaxInfoPage(
      key: PageStorageKey('Page2'),
    ),
    SettingsPage(
      key: PageStorageKey('Page3'),
    )
  ];

  final PageStorageBucket bucket = PageStorageBucket();

  int _selectedIndex = 0;

  Widget _bottomNavigationBar(int selectedIndex) => BottomNavigationBar(
        onTap: (int index) => setState(() => _selectedIndex = index),
        currentIndex: selectedIndex,
        items: const <BottomNavigationBarItem>[
          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,
      ),
    );
  }
}

页面:

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: () => Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => BottomNavigationBarController()), (Route route) => route == null),
        );
      },
    ),

因此,当我使用AppBar中的图标向后导航时。我将带我到第1页,而不是第2页

1 个答案:

答案 0 :(得分:0)

使用Navigator.of(context).pop();应该使您以正确的状态回到上一个屏幕。为了更好地理解它,请查看本文:https://medium.com/flutter-community/flutter-push-pop-push-1bb718b13c31

如果这不起作用,则必须保存BottomNavigationBar的当前索引,并将其返回给导航控制器。