Я не могу правильно настроить валидатор для регистрации и входа в проект flutter.IOS

Программируем под IOS
Ответить
Anonymous
 Я не могу правильно настроить валидатор для регистрации и входа в проект flutter.

Сообщение Anonymous »

Я вынес виджет TextFormFiled в отдельный класс и стили для него. по идее я правильно написал логику для валидатора, но она почему-то не работает, после нажатия на кнопку "Начать" если строка пустая, то должна появиться ошибка по этому поводу, а если почта не указана правильно, то пароль тот же, аналогично, но почему после нажатия на кнопку ничего не происходит
Вот строки кода:
class _SignUpPageState extends State {
final FirebaseAuthServices _auth = FirebaseAuthServices();
final _formKey = GlobalKey();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();

String? validateEmail(String? email) {
RegExp emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
final isEmailValid = emailRegex.hasMatch(email ?? '');
if (!isEmailValid) {
return "Please enter a valid email";
}
return null;
}

@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
_confirmPasswordController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: Stack(
children: [
Image.asset(
"assets/images/back_signup.png",
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
),
Center(
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
"Please enter your details",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 38,
fontFamily: "Montserrat",
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 22),
CustomTextField(
textColor: Colors.grey,
hintText: "Email",
controller: _emailController,
obscureText: false,
width: 326,
validator: validateEmail,
),
SizedBox(height: 18),
CustomTextField(
textColor: Colors.white,
controller: _passwordController,
hintText: "Password",
obscureText: true,
width: 326,
validator: (password) => password!.length < 6
? "Password must be at least 6 characters long"
: null,
),
SizedBox(height: 18),
CustomTextField(
textColor: Colors.white,
controller: _confirmPasswordController,
hintText: "Confirm Password",
obscureText: true,
width: 326,
validator: (password) => password!.length < 6
? "Password must be at least 6 characters long"
: null,
),
SizedBox(height: 18),
SizedBox(
width: 326,
height: 45,
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
_signUp();
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
),
child: Text(
"Get Started",
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontFamily: "Montserrat",
fontWeight: FontWeight.bold,
),
),
),
),
SizedBox(height: 24),
],
),
),
),
],
),
);
}

void _signUp() async {
String email = _emailController.text;
String password = _passwordController.text;
String confirmPassword = _confirmPasswordController.text;

if (password != confirmPassword) {
_showErrorDialog("Passwords do not match");
return;
}

User? user = await _auth.signUpWithEmailAndPassword(email, password);

if (user != null) {
print("User created: ${user.email}");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const HomePage(),
),
);
} else {
_showErrorDialog("Failed to create user");
}
}

void _showErrorDialog(String message) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("Error"),
content: Text(message),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("OK"),
),
],
);
},
);
}
}

Вот код виджета CustomTextField
@override

Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 15),
child: Center(
child: SizedBox(
width: widget.width ?? MediaQuery.of(context).size.width * 0.8,
height: widget.height,
child: Stack(
alignment: Alignment.centerRight,
children: [
TextFormField(
validator: widget.validator,
keyboardType: TextInputType.multiline,
controller: widget.controller,
obscureText: widget.obscureText && !_showPassword,
decoration: InputDecoration(
hintText: widget.hintText,
hintStyle: TextStyle(
color: Colors.grey,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(40),
borderSide: BorderSide(
color: Colors.white,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: BorderSide(
color: Colors.white,
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25),
borderSide: BorderSide(
color: Colors.red,
),
),
contentPadding: EdgeInsets.only(left: 16),
),
style: _style,
textAlign: TextAlign.left,
),
if (widget.obscureText)
IconButton(
onPressed: () {
setState(() {
_showPassword = !_showPassword;
});
},
icon: Icon(
_showPassword ? Icons.visibility : Icons.visibility_off,
color: Colors.grey,
),
),
],
),
),
),
);
}


Подробнее здесь: https://stackoverflow.com/questions/781 ... lutter-pro
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»