简体   繁体   English

如何在颤振中返回上一页

[英]How to back to previous page in flutter

I am new in Flutter.我是 Flutter 的新手。 When I press the device back button in my apps.当我在我的应用程序中按下设备返回按钮时。 It will direct exit the apps.它将直接退出应用程序。 How to go to the previous page like image before.如何像之前的图片一样转到上一页。 If I at Tab 3, when I press the device back button it will go to Tab 2. If I at Tab 1 press the back button, it will just exit the apps.如果我在 Tab 3,当我按下设备后退按钮时,它会转到 Tab 2。如果我在 Tab 1 按下后退按钮,它只会退出应用程序。 Anyone can help me?任何人都可以帮助我吗? Thanks in advance提前致谢

Use WillPopScope to handle back navigation使用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,
          ),
        ));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM