Is There Any Way Intercept 'back' Keydown In Flutter App On Android?
I need to show an alert dialog before user navigates away from current route by pressing Back button on Android devices. I tried to intercept back button behavior by implementing W
Solution 1:
I found the solution is to use WillPopScope
widget. Here is the final code below:
import'dart:async';
import'package:flutter/material.dart';
classNewEntryextendsStatefulWidget {
NewEntry({Key key, this.title}) :super(key: key);
final String title;
@override
State<StatefulWidget> createState() => new_NewEntryState();
}
class_NewEntryStateextendsState<NewEntry> {
Future<bool> _onWillPop() {
return showDialog(
context: context,
child: newAlertDialog(
title: newText('Are you sure?'),
content: newText('Unsaved data will be lost.'),
actions: <Widget>[
newFlatButton(
onPressed: () => Navigator.of(context).pop(false),
child: newText('No'),
),
newFlatButton(
onPressed: () => Navigator.of(context).pop(true),
child: newText('Yes'),
),
],
),
) ?? false;
}
@override
Widget build(BuildContext context) {
returnnewWillPopScope(
onWillPop: _onWillPop,
child: newScaffold(
appBar: newAppBar(
title: newText(widget.title),
),
floatingActionButton: newFloatingActionButton(
child: newIcon(Icons.edit),
onPressed: () {},
),
),
);
}
}
Solution 2:
The back_button_interceptor
package can simplify this for you and is especially useful in more complex scenarios.
https://pub.dev/packages/back_button_interceptor#-readme-tab-
Example usage:
@override
void initState() {
super.initState();
BackButtonInterceptor.add(myInterceptor);
}
@override
void dispose() {
BackButtonInterceptor.remove(myInterceptor);
super.dispose();
}
bool myInterceptor(bool stopDefaultButtonEvent) {
print("BACK BUTTON!"); // Do some stuff.
return true;
}
Solution 3:
If you are using the GetX package and you implemented the GetMaterialApp
method to initialize your app, the didPopRoute
and didPushRoute
methods in WidgetsBindingObserver
never get called. Use the routingCallback
instead, below is an example, for more info check out GetX documentation:
GetMaterialApp(
routingCallback: (routing) {
routing.isBack ? didPopRoute() : didPushRoute(routing.current);
}
)
Post a Comment for "Is There Any Way Intercept 'back' Keydown In Flutter App On Android?"