[英]Back Button not working inside Webview in flutter
I wrote the code by wrapping willpopScope so that I can get previous page of webview but it is not working thus it is closing the entire webView page.我通过包装 willpopScope 编写了代码,以便我可以获得 webview 的上一页,但它不起作用,因此它正在关闭整个 webView 页面。
Here is the full code:这是完整的代码:
class Resources extends StatefulWidget {
@override
_ResourcesState createState() => _ResourcesState();
}
class _ResourcesState extends State<Resources> {
late WebViewController _controller;
final Completer<WebViewController> _controllerCompleter =
Completer<WebViewController>();
Future<bool> pop(BuildContext context) async {
if (await _controller.canGoBack()) {
_controller.goBack();
return Future.value(false);
} else {
return Future.value(true);
}
}
@override
void initState() {
super.initState();
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: WillPopScope(
onWillPop:()=> pop(context),
child: Scaffold(
appBar: AppBar(),
body: WebView(
gestureNavigationEnabled: true,
initialUrl: 'https://www.edhitch.com/login.html',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controllerCompleter.future.then((value) => _controller = value);
_controllerCompleter.complete(webViewController);
},
),
),
),
),
);
}
}
I have used will scope which takes bool function pop kindly help me out with it.我用过将 scope 需要 bool function pop 请帮助我。
Try to below code hope it helps to you:试试下面的代码希望对你有帮助:
Create Future function using async and it will return true使用 async 创建 Future function 它将返回 true
Future<bool> onWillPopFunction() async {
return true;
}
and call your onWillPopFunction, function on onWillPop event并在 onWillPop 事件上调用您的 onWillPopFunction、function
WillPopScope(
child: Scaffold(),
onWillPop: onWillPopFunction,
)
you also add alert box for warning like (exit your app or not?)您还添加了警告框,例如(退出您的应用程序吗?)
Or try below code或者试试下面的代码
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.pop(context, false),
),
You need to set the controller when the WebView is created and pop for the controller, not the app context:您需要在创建 WebView 时设置 controller 并为 controller 弹出,而不是应用程序上下文:
onWillPop: (){
_controller.goBack();
},
(updated, since "Controller.complete()" does not exist anymore) (已更新,因为“Controller.complete()”不再存在)
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.