繁体   English   中英

后退按钮在 flutter 中的 Webview 内不起作用

[英]Back Button not working inside Webview in flutter

我通过包装 willpopScope 编写了代码,以便我可以获得 webview 的上一页,但它不起作用,因此它正在关闭整个 webView 页面。

这是完整的代码:



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);

                    },
                ),

              ),
          ),
            ),
        );
  }
}

我用过将 scope 需要 bool function pop 请帮助我。

试试下面的代码希望对你有帮助:

使用 async 创建 Future function 它将返回 true

Future<bool> onWillPopFunction() async {
    return true;
}

并在 onWillPop 事件上调用您的 onWillPopFunction、function

WillPopScope(
    child:  Scaffold(), 
    onWillPop: onWillPopFunction,
)

您还添加了警告框,例如(退出您的应用程序吗?)

或者试试下面的代码

 IconButton(
      icon: Icon(Icons.arrow_back),
      onPressed: () => Navigator.pop(context, false),
    ),

您需要在创建 WebView 时设置 controller 并为 controller 弹出,而不是应用程序上下文:

onWillPop: (){
    _controller.goBack();
},

(已更新,因为“Controller.complete()”不再存在)

onWebViewCreated: (WebViewController webViewController) {
    _controller = webViewController;
},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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