Flutter Do Not Use BuildContexts Across Async Gaps

1.问题

flutter在使用新版本时,遇见

Don't use 'BuildContext's across async gaps.nTry rewriting the code to not use the 'BuildContext', or guard the use with a 'mounted' check

的问题。

这意味着在异步操作之后不应该再使用 BuildContext

因为提供该上下文的widget可能已经不在widget树中。如果你尝试访问它的上下文或者在其中进行路由,可能会导致潜在的错误或者崩溃。

2.解决方案

检查mounted的属性

对于Widget而言


void _onButtonPressed(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const DetailPage(
data: 'Hello from PageOne',
)));

if (!context.mounted) {
return;
}

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('receive result:$result')),
);
}


原文始发于微信公众号(ksnowlv):Flutter Do Not Use BuildContexts Across Async Gaps

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/254469.html

(0)
Java朝阳的头像Java朝阳

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!