不要在Flutter的showDialog周围的异步间隙中使用’BuildContext’。

huangapple go评论64阅读模式
英文:

Don't use 'BuildContext' across async gaps around showDialog in Flutter

问题

我在我的Flutter项目中的每个InAppWebView小部件内都会得到这个警告,显示为showDialog小部件。如何解决这个问题?

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

          if (requestFocusNodeHrefResult != null) {
            // 不要在异步间隔中使用 'BuildContext'
            showDialog(
              context: context,
              builder: (context) {
                return LongPressAlertDialog(
                  webViewModel: widget.webViewModel,
                  hitTestResult: hitTestResult,
                  requestFocusNodeHrefResult: requestFocusNodeHrefResult,
                );
              },
            );
          }
        }
      },
}
英文:

I'm getting this warning in my flutter project around every showDialog widget inside InAppWebView Widget. How to solve this ?

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

答案1

得分: 5

尝试这样做:

if (requestFocusNodeHrefResult != null && context.mounted) { // <=== 添加这一行
  showDialog(
    context: context,
    builder: (context) {
      return LongPressAlertDialog(
        webViewModel: widget.webViewModel,
        hitTestResult: hitTestResult,
        requestFocusNodeHrefResult: requestFocusNodeHrefResult,
      );
    },
  );
}
英文:

try this:

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

huangapple
  • 本文由 发表于 2023年2月9日 01:47:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定