![](/img/trans.png)
[英]I am using flutter version 3.3.5. and I am getting this error message "Do not use BuildContexts across async gaps." for the code below
[英]Do not use BuildContexts across async gaps. After update pub yaml to the major version
我已將 pub yaml 升級到主要版本flutter pub upgrade --major versions
,它給了我很多建議錯誤,我不明白為什么? 有人可以解釋嗎?
這是一個例子。 它說Do not use BuildContexts across async gaps
我想在這里做什么。
_resetEmail(String password,) async {
final user = FirebaseAuth.instance.currentUser;
final credential =
EmailAuthProvider.credential(email: user!.email!, password: password);
try {
UserCredential;
await FirebaseAuth.instance.currentUser
?.reauthenticateWithCredential(credential);
///The problem is here
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: const ResetEmailScreen()));
///
} on FirebaseAuthException {
Fluttertoast.showToast(
msg: 'Wrong password',
gravity: ToastGravity.TOP,
toastLength: Toast.LENGTH_LONG,
backgroundColor: Colors.grey[400],
textColor: Colors.black,
);
}
}
在 Navigator.push 之前添加條件if (mounted)
。 您正在異步方法中使用上下文。 在執行此方法時,上下文可能會發生變化。 但是這個上下文被傳遞給導航器。 因此我認為錯誤..
將 BuildContext 存儲在方法中會導致異步間隙,如果應用程序崩潰,以后可能會難以找到問題。
因此,當從 StatefulWidget 使用 BuildContext 時,必須在異步間隙后檢查 mount 屬性。
解決方案
使用“if (!mounted) return;” 在使用上下文之前。
if (!mounted) return;
Navigator.push(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: const ResetEmailScreen()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.