【问题标题】:Back Button not working inside Webview in flutter后退按钮在颤动中无法在 Webview 中工作
【发布时间】:2021-10-13 08:01:16
【问题描述】:

我通过包装 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);

                    },
                ),

              ),
          ),
            ),
        );
  }
}

我使用了带有 bool 函数 pop 的 will scope,请帮助我。

【问题讨论】:

    标签: flutter dart flutter-dependencies dart-html dart-null-safety


    【解决方案1】:

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

    使用 async 创建 Future 函数,它会返回 true

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

    并在 onWillPop 事件上调用你的 onWillPopFunction 函数

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

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

    或者试试下面的代码

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

    【讨论】:

    • 没有帮助我想返回上一个网页,而不是关闭整个网页。
    • @HarshKumarYadav 查看我对 IconButton 的更新答案
    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多