【问题标题】:flutter navigate back to selected page颤振导航回所选页面
【发布时间】:2019-08-06 02:45:47
【问题描述】:

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

导航控制器:

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 页

【问题讨论】:

    标签: flutter


    【解决方案1】:

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

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

    【讨论】:

    • 当我使用Navigator.of(context).pop(); 时,我得到的只是黑屏。我不确定后者该怎么做。
    • 如何导航到第二页?使用 Navigator.popAndRemoveUntil(...); 将从堆栈中删除页面,您可能无法使用 pop() 回到它。阅读我在回答中链接的 Medium 文章将帮助您理解我的意思!
    猜你喜欢
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2020-07-14
    • 2021-11-24
    • 2021-05-21
    • 1970-01-01
    • 2019-06-04
    • 2020-10-10
    相关资源
    最近更新 更多