dipgirl
dipgirl

Reputation: 690

How to back to previous page in flutter

I am new in 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. Anyone can help me? Thanks in advance

Upvotes: 0

Views: 273

Answers (1)

Alex Sunder Singh
Alex Sunder Singh

Reputation: 2574

Use WillPopScope to handle back navigation

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,
          ),
        ));
  }
}

Upvotes: 2

Related Questions