Я вынес виджет 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
Я не могу правильно настроить валидатор для регистрации и входа в проект flutter. ⇐ IOS
Программируем под IOS
1710732721
Anonymous
Я вынес виджет TextFormFiled в отдельный класс и стили для него. по идее я правильно написал логику для валидатора, но она почему-то не работает, после нажатия на кнопку "Начать" если строка пустая, то должна появиться ошибка по этому поводу, а если почта не указана правильно, то пароль тот же, аналогично, но почему после нажатия на кнопку ничего не происходит
[b]Вот строки кода:[/b]
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,
),
),
],
),
),
),
);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78149507/i-cant-set-up-the-validator-correctly-to-register-and-log-in-to-the-flutter-pro[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия