不要在Flutter中的showDialog周围跨异步间隙使用“BuildContext”

3phpmpom  于 2023-02-09  发布在  Flutter
关注(0)|答案(1)|浏览(172)

在我的flutter项目中,InAppWebView小部件中的每个showDialog小部件都会出现此警告。如何解决此问题?

return InAppWebView(
 ...
   onLongPressHitTestResult: (controller, hitTestResult) async {
        if (LongPressAlertDialog.hitTestResultSupported
            .contains(hitTestResult.type)) {
          var requestFocusNodeHrefResult =
              await _webViewController?.requestFocusNodeHref();

          if (requestFocusNodeHrefResult != null) {
//Don't use 'BuildContext' across async gaps
            showDialog(
              context: context,
              builder: (context) {
                return LongPressAlertDialog(
                  webViewModel: widget.webViewModel,
                  hitTestResult: hitTestResult,
                  requestFocusNodeHrefResult: requestFocusNodeHrefResult,
                );
              },
            );
          }
        }
      },
}
c8ib6hqw

c8ib6hqw1#

试试这个:

if (requestFocusNodeHrefResult != null && context.mounted) { // <=== add this
    showDialog(
      context: context,
      builder: (context) {
        return LongPressAlertDialog(
          webViewModel: widget.webViewModel,
          hitTestResult: hitTestResult,
          requestFocusNodeHrefResult: requestFocusNodeHrefResult,
        );
      },
    );
  }

相关问题