Reputation: 844
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!");
})
);
}
}
Upvotes: 3
Views: 4310
Reputation: 6142
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;
},
);
}
Upvotes: 12