Keshav Aditya R P
Keshav Aditya R P

Reputation: 3221

How to go to the previous Tab when the Device Back Button is pressed in Flutter?

Let's say I click on the tab "Page 2" and then "Page 3". Now when I click the back button on the device I want to go back to "Page 2".

What happens for me is that the app closes. Am I using the wrong Widget or what should I do to ensure when the user uses the back button on the device it goes to the previous tab and not force close the app.

class MovieRouting extends StatefulWidget {
  @override
  MovieRoutingState createState() => new MovieRoutingState();
}

// SingleTickerProviderStateMixin is used for animation
class MovieRoutingState extends State<MovieRouting> with SingleTickerProviderStateMixin {
  int i = 0;
  var pages = [new Page1(), new Page2(), new Page3(), new Page4()];   

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {  

    return new Scaffold(
      body: pages[i],
      // drawer: new AppNavigationDrawer(),
      bottomNavigationBar: new BottomNavigationBar(
        items: [
          new BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            title: new Text('page 1'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.photo_library),
            title: new Text('page 2'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.book),
            title: new Text('page 3'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.notifications),
            title: new Text('page 4'),
          ),
        ],
        currentIndex: i,
        type: BottomNavigationBarType.fixed,
        onTap: (index) {
          print (index);
          setState(() {
            i = index;
          });
        },
      ),
    );

  }
}

Upvotes: 1

Views: 5167

Answers (2)

amff
amff

Reputation: 115

This is an alternative way to control back button, when its pressed it goes to first tab and after that if its pressed again within 2 sec it will close the app(or whatever you want to do) define a bool var in your state class, wrap your scaffold with WillPopScope widget, pass the _onWillPop() function as its OnwillPop attribute.

  bool canback = false;

return WillPopScope(
            child: Scaffold(...),
            onWillPop: _onWillPop);

 Future<bool> _onWillPop() async {

    if (canback == true) {
      SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }else{
      setState(() {
        index=0;
      });
    }

    Timer(Duration(seconds: 2), () {
      setState(() {
        canback = false;
      });
    });
    canback = true;
  }

Upvotes: 2

Saed Nabil
Saed Nabil

Reputation: 6861

this is the modified code will give you one step back

import 'package:flutter/material.dart';

  void main() => runApp(MyApp());

  class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MovieRouting(),
      );
    }
  }

  class Page1 extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Container(child: Text('page1'),);
    }
  }

  class Page2 extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Container(child: Text('page2'),);
    }
  }
  class Page3 extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Container(child: Text('page3'),);
    }
  }
  class Page4 extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Container(child: Text('page4'),);
    }

  }
  class MovieRouting extends StatefulWidget {
    @override
    MovieRoutingState createState() => new MovieRoutingState();
  }

  // SingleTickerProviderStateMixin is used for animation
  class MovieRoutingState extends State<MovieRouting> with SingleTickerProviderStateMixin {
    int i = 0;
    int _pState = 0;
    var pages = [new Page1(), new Page2(), new Page3(), new Page4()];

    @override
    void initState() {
      super.initState();
    }
    Future<bool> _onWillPop() {
      setState(() {
        i=_pState;
      });


    }

    @override
    Widget build(BuildContext context) {

      return WillPopScope(
        onWillPop: _onWillPop ,
        child: new Scaffold(
          body: pages[i],
          // drawer: new AppNavigationDrawer(),
          bottomNavigationBar: new BottomNavigationBar(
            items: [
              new BottomNavigationBarItem(
                icon: new Icon(Icons.home),
                title: new Text('page 1'),
              ),
              new BottomNavigationBarItem(
                icon: new Icon(Icons.photo_library),
                title: new Text('page 2'),
              ),
              new BottomNavigationBarItem(
                icon: new Icon(Icons.book),
                title: new Text('page 3'),
              ),
              new BottomNavigationBarItem(
                icon: new Icon(Icons.notifications),
                title: new Text('page 4'),
              ),
            ],
            currentIndex: i,
            type: BottomNavigationBarType.fixed,
            onTap: (index) {
              print (index);
              setState(() {
                _pState = i;
                i = index;

              });
            },
          ),
        ),
      );

    }
  }

Upvotes: 2

Related Questions