import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:authentication_signup/components/my_button.dart';
import 'package:authentication_signup/components/my_textfield.dart';
import 'package:authentication_signup/components/square_tile.dart';
class LoginPage extends StatefulWidget {
const LoginPage({super.key});
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
//text editing controllers
final usernameController = TextEditingController();
final passwordController = TextEditingController();
//sign user in method
void signUserIn() async {
//loading circle
showDialog(context: context, builder: (context) {
return const Center(
child: CircularProgressIndicator(),
);
},);
try {
// Try signing in
await FirebaseAuth.instance.signInWithEmailAndPassword(
email: usernameController.text,
password: passwordController.text,
);
// Close the loading dialog only if the widget is still mounted
if (mounted) {
Navigator.pop(context);
}
} on FirebaseAuthException catch (e) {
// Close the loading dialog only if the widget is still mounted
if (mounted) {
Navigator.pop(context);
}
// Handle error
if (e.code == 'user-not-found') {
// Show error to user
wrongEmailMessage();
} else if (e.code == 'wrong-password') {
// Show error to user
wrongPasswordMessage();
}
} catch (e) {
// Handle any other exceptions and close the loading dialog if mounted
if (mounted) {
Navigator.pop(context);
}
print('Error: $e');
}
}
// Wrong email message pop-up
void wrongEmailMessage() {
if (mounted) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text('Incorrect email'),
content: Text('No user found with that email.'),
);
},
);
}
}
// Wrong password message pop-up
void wrongPasswordMessage() {
if (mounted) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text('Incorrect password'),
content: Text('The password you entered is incorrect.'),
);
},
);
}
}
确保小部件已安装:如果在异步操作期间已卸载小部件,则尝试显示对话框将失败。在调用
Navigator.pop(context)
或显示对话框之前,请务必检查小部件是否仍已安装。
异步间隙:异步操作(例如使用 Firebase 登录)可能会导致 BuildContext 出现问题。使用 Mounted 属性检查小部件是否仍在树中。
Flutter Build Context:确保在调用 Navigator 或 showDialog 时使用正确的 BuildContext。
我尝试了这些并更新了代码,但当我输入错误的电子邮件或密码时,对话框仍然没有显示。它只是不登录并停留在登录页面本身,没有为用户弹出对话框
我认为你的代码应该可以正常工作,但你错过了逻辑处理!
如果在
auth
阶段发生任何异常您已经弹出了加载对话框。
因此,在调用这些方法
wrongPasswordMessage()
和 wrongEmailMessage()
时,由于这种情况,将不会显示错误对话框:
void wrongPasswordMessage() {
if (mounted) {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text('Incorrect password'),
content: Text('The password you entered is incorrect.'),
);
},
);
}
}
如果屏幕为
mounted
但未安装,因为您已弹出加载对话框,您将显示该对话框。
所以,我认为删除两种错误方法中的
if condition
将会出现错误对话框,或者您可以将该条件更改为:
if(!mounted){
// show that dialog
}