Reputation: 803
I use the below code for a Flutter Webview (webview_flutter package).
When a Back button is clicked, _goBack() sets whether to go back to the previous page, or if no previous page, pops the webview.
I then enabled gestureNavigationEnabled:true to allow the user to swipe back to previous pages. Works well. However, when there are no previous pages, swiping does not pop the webview.
Is there a way to give swiping back the same behavior as the Back button?
Thank you.
import 'package:webview_flutter/webview_flutter.dart';
body: WillPopScope(
onWillPop: () => _goBack(context),
child: WebView(
initialUrl: widget.url,
gestureNavigationEnabled: true,
onWebViewCreated: (WebViewController webViewController) {
_controllerCompleter.future.then((value) => _controller = value);
_controllerCompleter.complete(webViewController);
),
),
Future<bool> _goBack(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
Navigator.of(context).pop();
return Future.value(true);
}
}
Upvotes: 2
Views: 1867
Reputation: 4750
The Problem is the 'Context' when it found no context it doesnt close the webview window .so in this case what you need to do is :
Look at this here: https://github.com/brianegan/flutter_redux/issues/5#issuecomment-361215074
You can set a global key for your navigation:
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
Pass it to MaterialApp:
new MaterialApp(
title: 'MyApp',
onGenerateRoute: generateRoute,
navigatorKey: navigatorKey,
);
Push routes:
navigatorKey.currentState.pushNamed('/someRoute');
You Need to Create a Global Key for Navigation and then it can work . it will close the window without getting the context (means if the previous page is not there then it can also pop the window )
Upvotes: 0