在构建小部件外显示错误消息



我使用Model类在注册或登录之前对用户进行身份验证。问题是我不知道如何在snackbar中向用户打印错误消息,因为在这个类中没有定义小部件。

如何从模型类向用户显示错误信息?

模型类:

class FireAuth {

static Future<User> registerUsingEmailPassword({
String name,
String email,
String password,
}) async {
FirebaseAuth auth = FirebaseAuth.instance;
User user;
try {
UserCredential userCredential = await auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
user = userCredential.user;
await user.updateDisplayName(name);
await user.reload();
user = auth.currentUser;
//check if email is registered before
//add user data to firestore
CollectionReference users = FirebaseFirestore.instance.collection('users');
users.doc(user.uid).set({
'uid':user.uid,
'img_url':'0',
'name': name,  
'phone': '',  
'email': email, 
'job_title':'',
'university':'',
'procedures':'',
'expert_in':'',
})
.then((value) => print("User Added"))
.catchError(
(error) => print("Failed to add user: $error"));

} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');

}
} catch (e) {
print(e);
}
return user;
}
}

我需要'The account already exists for that email.'错误信息显示给用户,而不仅仅是在日志中打印。

问得好,我尽量笼统地回答,以便对你们处理这个非常重要的案件的整体模式有利。

依赖于BuildContext是颤振中常见的不便。它经常出现,但有很好的理由。您可以这样考虑:您需要上下文,因为您需要指定UI将在树中的哪个位置显示。知道如何处理这些情况使得初学者和更高级的扑动开发人员的区别。

所以一种方法是传递BuildContext,但我不建议这样做。

假设我有一个函数foo,它返回一些Future,而不是改变函数的签名来接受上下文,您可以简单地等待函数并在已经在UI中的回调中使用上下文。例如,

不是


Future foo(BuildContext context) {
try {
// await some async process
// Use context to show success.
} catch (e) {
// Use context to show failure.
}
}

你可以这样做

GestureDetector(
onTap: () async {
try {
await foo();
// Use context to show success.
} catch (e) {
// Use context to show failure.
}         
},
child: // some child
),
关键是在第二个示例中,上下文已经存在于小部件中。foo的签名更简单。它需要一些重组。在这里,我假设这一系列事件可以追溯到GestureDetector,但它也可以是其他任何东西。

相关内容