Albert
Albert

Reputation: 25

Android back button action

I'm dealing with back actions. I'm not able to achieve good results with WillPopScope() (it's only called with top app return button but not called with android back button). In my app, I have several pages and when android back button is pressed, I don't see the previous page. For example, I have main-page1-page2-page3 If I'm in page 3 and press Android back button I return to page1, not to page2. In other cases it returns to main...How it is possible? Is there a way to define de pages "order"?

EDIT This is my code that I shared in a previous question.

class Calendario1 extends StatelessWidget {
  final List listaini;
  Calendario1(this.listaini);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "ATGapp",
      home:Cal1(listaini: listaini),
    );
  }
}

class Cal1 extends StatefulWidget {
  final List listaini;
  Cal1({Key? key,required this.listaini}) : super(key: key);

  @override
  ///
  _Cal1State createState() => _Cal1State();
}

class _Cal1State extends State<Cal1> {
  @override
  void initState() {
    getImage(path1);
    super.initState();
  }

  String url_1 = '';

  getImage(String path1) async {
    //String url='';
    final ref1 = FirebaseStorage.instance.ref().child(path1);
    var url1 = await ref1.getDownloadURL();
    setState(() => url_1 = url1);
  }

  final FirebaseStorage storage =
      FirebaseStorage.instance;
  String path1 = 'fondos/mons.jpeg';

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        print('Bck button pressed');
        return false;
      },
      child: Scaffold(
          body: Column(...//and so on

Upvotes: 0

Views: 293

Answers (2)

Albert
Albert

Reputation: 25

Thank your for all your help. The final solution has been a new structure of the app pages. Until now, every page was a different dart file and with this structure, the behaviour of willpopscope and any other solutions didn't work for me. Now, all pages are in the same file ordered by routes definitions in MaterialApp. Now, I'm able to catch the android back button click and work with it. I hope this can be helpful for others.

Upvotes: 0

Phanindra
Phanindra

Reputation: 1378

add Navigator.pop() inside onWillPop and return true.

onWillPop: () async {
       // do something here
        return true;
      },


return new WillPopScope(
    onWillPop: _willPopCallback,
    child: new Scaffold(
     //then the rest of your code...

Upvotes: 0

Related Questions