【问题标题】:How to back to previous page in flutter如何在颤动中返回上一页
【发布时间】:2020-03-03 13:47:07
【问题描述】:

我是 Flutter 的新手。当我在我的应用程序中按下设备返回按钮时。它将直接退出应用程序。如何像以前的图像一样转到上一页。如果我在选项卡 3,当我按下设备返回按钮时,它将转到选项卡 2。如果我在选项卡 1 按下返回按钮,它只会退出应用程序。任何人都可以帮助我吗?提前致谢

【问题讨论】:

    标签: flutter


    【解决方案1】:

    使用WillPopScope 处理后退导航

    class _TabsControllerState extends State<TabsController> {
      final List<Widget> pages = [
        TabOne(
          key: PageStorageKey('page1'),
        ),
        TabTwo(
          key: PageStorageKey('page2'),
        ),
        TabThree(
          key: PageStorageKey('page3'),
        ),
      ];
    
      final PageStorageBucket bucket = PageStorageBucket();
    
      var _selectedIndex = 0;
    
      Widget _bottomNavigationBar(var selectedIndex) => BottomNavigationBar(
            onTap: (var index) => setState(() => _selectedIndex = index),
            currentIndex: selectedIndex,
            type: BottomNavigationBarType.fixed,
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(icon: Icon(Icons.apps), title: Text('Tab 1')),
              BottomNavigationBarItem(icon: Icon(Icons.apps), title: Text('Tab 2')),
              BottomNavigationBarItem(icon: Icon(Icons.apps), title: Text('Tab 3')),
            ],
          );
    
      @override
      Widget build(BuildContext context) {
        return WillPopScope(
            onWillPop: ()async{
              if(_selectedIndex == 0)
              return true;
              else setState(() {
                _selectedIndex -= 1;
              });
              return false;
            },
            child: Scaffold(
              bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
              body: PageStorage(
                child: pages[_selectedIndex],
                bucket: bucket,
              ),
            ));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 1970-01-01
      • 2019-11-05
      • 2021-08-18
      • 2020-05-06
      • 2020-12-02
      • 2016-05-28
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多