当前位置:网站首页>Flutter 返回按钮的监听

Flutter 返回按钮的监听

2022-07-04 20:35:00 海阔天空6688

物理按钮和返回按钮的监听

Flutter 返回按钮的监听是通过 WillPopScope来实现的

class BackDemoState extends State<BackDemoWidget> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
          appBar: AppBar(
            title: const Text("返回键监听"),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: (){
                SmartDialog.showToast("返回");
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                } else {
                  SystemNavigator.pop();
                }
              },
            ),
          ),
        ));
  }

  Future<bool> _onWillPop() {
    SmartDialog.showToast("返回");
    if (Navigator.canPop(context)) {
      Navigator.pop(context);
    } else {
      SystemNavigator.pop();
    }
    return Future.value(false);
  }
}

WebView的返回监听

 @override
  Widget build(BuildContext context) {
    return FutureBuilder<WebViewController>(
        future: _controller.future,
        builder: (context, snapshot) {
          return WillPopScope(
            onWillPop: () async {
              if (snapshot.hasData) {
                final bool canGoBack = await snapshot.data!.canGoBack();
                if (canGoBack) {
                  // 网页可以返回时,优先返回上一页
                  await snapshot.data!.goBack();
                  return Future.value(false);
                }
              }
              return Future.value(true);
            },
            child: Scaffold(
              appBar: AppBar(
                title: Text(widget.title),
              ),
              body: Stack(
                children: [
                  WebView(
                    initialUrl: "https://www.baidu.com",
                    javascriptMode: JavascriptMode.unrestricted,
                    allowsInlineMediaPlayback: true,
                    onWebViewCreated: (WebViewController webViewController) {
                      _controller.complete(webViewController);
                    },
                    onProgress: (int progress) {
                      debugPrint('WebView is loading (progress : $progress%)');
                      setState(() {
                        _progressValue = progress;
                      });
                    },
                  ),
                  if (_progressValue != 100) LinearProgressIndicator(
                    value: _progressValue / 100,
                    backgroundColor: Colors.transparent,
                    minHeight: 2,
                  ) else Gaps.empty,
                ],
              ),
            ),
          );
        }
    );
  }
原网站

版权声明
本文为[海阔天空6688]所创,转载请带上原文链接,感谢
https://haikuotiankong.blog.csdn.net/article/details/125598453