简体   繁体   中英

Flutter: Add result to Navigator when system back button is pressed

In my example app below, I have two routes: HomeRoute and OtherRoute . I want OtherRoute to always return a result when it is popped from the navigator. In this example, it does this when the RaisedButton in OtherRoute is pressed. However, I also want it to return a result when the back button is pressed. I know I can override the back button on the AppBar , but I also want to override the behavior of the "system" back button on Android.

I know I can use WillPopScope to prevent the system back button from popping the current route, but I do not want this. If possible, I want the system back button to still be able to pop the current route, just with a result included. Is this possible?

Here is my sample app:

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: 'Test',
      home: Scaffold(
        appBar: AppBar(title: Text("Home"),),
        body: HomeRoute(),
      ),
    );
  }
}

class HomeRoute extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return RaisedButton(onPressed: (){
      Navigator.push(context, MaterialPageRoute(builder: (context){
        return OtherRoute();
      })).then((result){
        // I want result here to never be null
        Scaffold.of(context).showSnackBar(SnackBar(content: Text("$result")));
      });
    });
  }
}

class OtherRoute extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Other route"),),
      body: RaisedButton(onPressed: (){
        Navigator.pop(context, "Result!");
      })
    );
  }
}

Wrap your scaffold with WillPopScope in OtherRoute and override onWillPop method as follows:

@override
Widget build(BuildContext context) {
  return WillPopScope(
      //....
    ),
    onWillPop: () async {
      Navigator.pop(context, "Result!");
      return false;
    },
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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