我有一个带有firebase身份验证和错误验证的登录屏幕。当用户插入凭据时,firebase进行验证并返回错误代码。我正在翻译错误,然后将其显示在小吃店。我的问题是点击登录按钮,我想要的进度指标出现,如果有任何错误捕获,它必须停止,只有小吃店必须显示。我的代码如下
myButtonOnPressed: () async {
try {
final newUser = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
if (newUser != null) {
Navigator.pushNamed(context, HomeScreen.id);
}
} on FirebaseAuthException catch (e) {
///look for error conde in switch statement and return
///english error code
String fireBaseAuthErrorCode = funcFireBaseAuthErrors(e.code);
ScaffoldMessenger.of(context).showSnackBar(
///add SnackBar function
funcSnackBar(
errorMessage: fireBaseAuthErrorCode,
snackBarColor: Color(snackBarColor),
snackBarTextColor: Color(snackBarTextColor),
snackBarTextFont: snackBarTextFont,
snackBarTextSize: snackBarTextSize,
showErrorDuration: kLoginScreenSnackBarDisplayDuration,
),
);
}
},
我到底该怎么做?
我假设您正在使用StatefulWidget
-使用它可以通过布尔变量和按钮中的条件呈现来实现。
class YourWidget extends StatefulWidget {
const YourWidget({Key? key}) : super(key: key);
@override
State<YourWidget> createState() => _YourWidgetState();
}
class _YourWidgetState extends State<YourWidget> {
bool authInProgress = false;
Future<void> login() async {
try {
// Initiate login by setting authInProgress to true.
setState(() {
authInProgress = true;
});
final newUser = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
if (newUser != null) {
Navigator.pushNamed(context, HomeScreen.id);
}
} on FirebaseAuthException catch (e) {
///look for error conde in switch statement and return
///english error code
String fireBaseAuthErrorCode = funcFireBaseAuthErrors(e.code);
ScaffoldMessenger.of(context).showSnackBar(
///add SnackBar function
funcSnackBar(
errorMessage: fireBaseAuthErrorCode,
snackBarColor: Color(snackBarColor),
snackBarTextColor: Color(snackBarTextColor),
snackBarTextFont: snackBarTextFont,
snackBarTextSize: snackBarTextSize,
showErrorDuration: kLoginScreenSnackBarDisplayDuration,
),
);
} finally {
// Regardless of the outcome, after the process is done,
// set authInProgress to false.
setState(() {
authInProgress = false;
});
}
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: login,
child: authInProgress
? const CircularProgressIndicator()
: const Text("Login"),
);
}
}
- 创建变量
authInProgress
,初始值为false
,表示进程尚未开始 - 在登录功能中,使用
setState
方法将try
块中的authInProgress
设置为true
,并添加finally
块,将其设置回false
。不管try
块的结果如何,finally
块都会执行。因此,在这种情况下-无论登录失败或成功,finally块总是被执行。 - 我在这种情况下使用了
ElevatedButton
,在这种情况下,如果authInProgress
是true
,我们将渲染CircularProgressIndicator()
,否则Text()
,你想要显示。
注:
- 为了简洁起见,我在
build()
之外写了login()
。