Flutter、Provider 和 Firebase
我正在编写代码以使用提供程序包和 Fire Base 服务来处理用户的登录和注册,但我无法似乎无法创建新用户,然后我的代码确实会提醒用户错误陷入验证器中,我想要实现的只是我是否能够使用用户名、电子邮件注册用户并使用提供商验证其密码。
class UserDao extends ChangeNotifier {
final auth = FirebaseAuth.instance;
bool isLoggedIn() {
return auth.currentUser != null;
}
String? userId() {
return auth.currentUser?.uid;
}
String? email() {
return auth.currentUser?.email;
}
void signup(String email, String password) async {
try {
await auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => {writedDetailsToFirestore()})
.catchError((e) {
Fluttertoast.showToast(msg: e!.message);
});
notifyListeners();
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
if (kDebugMode) {
print('The password provided is too weak.');
}
} else if (e.code == 'email-already-in-use') {
if (kDebugMode) {
print('The account already exists for that email.');
}
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
}
void login(String email, String password) async {
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
notifyListeners();
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
if (kDebugMode) {
print('The password provided is too weak.');
}
} else if (e.code == 'email-already-in-use') {
if (kDebugMode) {
print('The account already exists for that email.');
}
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
}
void logout() async {
await auth.signOut();
notifyListeners();
}
}
这就是屏幕代码的样子,我重复了一遍,因为我希望它显示为一个块,尽管感觉像是自己做的。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
class RegisterScreen extends StatefulWidget {
const RegisterScreen({Key? key}) : super(key: key);
@override
State<RegisterScreen> createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _confirmController = TextEditingController();
final TextEditingController _userNameController = TextEditingController();
final formkeyOnRegister = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
final userDao = Provider.of<UserDao>(context, listen: false);
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.all(10),
child: Form(
key: formkeyOnRegister,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 300,
child: Image.asset('assets/logo.png'),
),
const SizedBox(
height: 20,
),
TextFormField(
textCapitalization: TextCapitalization.none,
autofocus: false,
controller: _userNameController,
obscureText: false,
onSaved: (value) {
_userNameController.text = value!;
},
validator: (value) {
if (value!.isEmpty) {
return 'Please fill in Username';
}
{
return null;
}
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(CupertinoIcons.person),
labelText: 'Username',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
TextFormField(
autofocus: false,
textCapitalization: TextCapitalization.none,
controller: _emailController,
onSaved: (value) {
_emailController.text = value!;
},
validator: (value) {
if (value!.isEmpty) {
return 'Email is empty';
}
if (!RegExp(
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
.hasMatch(value)) {
'Please enter valid email';
}
{
return null;
}
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(Icons.email_outlined),
labelText: 'Email',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
//Password field
TextFormField(
textCapitalization: TextCapitalization.none,
autofocus: false,
controller: _passwordController,
obscureText: true,
onSaved: (value) {
_passwordController.text = value!;
},
validator: (value) {
RegExp regex = RegExp(r'^.{6,}$');
if (value!.isEmpty) {
return ("Password is required");
}
if (!regex.hasMatch(value)) {
return ("Enter Valid Password(Min. 6 Characters");
}
return null;
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(CupertinoIcons.lock),
labelText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
// confirm password
TextFormField(
textCapitalization: TextCapitalization.none,
autofocus: false,
controller: _confirmController,
obscureText: true,
onSaved: (value) {
_passwordController.text = value!;
},
validator: (value) {
if (_confirmController.text !=
_passwordController.text) {
return "Password don't match";
}
return null;
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(CupertinoIcons.lock),
labelText: 'Confirm Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
Material(
borderRadius: BorderRadius.circular(30),
color: const Color.fromARGB(255, 207, 19, 5),
child: MaterialButton(
onPressed: () {
userDao.signup(_emailController.text,
_passwordController.text);
},
minWidth: MediaQuery.of(context).size.width * 0.5,
child: const Text(
'REGISTER',
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.w600),
)),
),
const SizedBox(
height: 20,
),
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"I already have an account. ",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w200),
),
GestureDetector(
onTap: () {
Navigator.pushReplacementNamed(
context, "login");
},
child: const Text(
"LOGIN",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w200,
color: Color.fromARGB(255, 207, 19, 5),
),
))
],
),
)
],
)),
),
),
),
);
}
}
I am writing code to using the provider package and fire base services to handle login and signup of the users but i can't have can't seem to be able to create the new user and then my code does alert the user of the errors caught in the validator, all am trying to achieve is if i can be able to sign up a user with a username, email and validate his password using provider.
class UserDao extends ChangeNotifier {
final auth = FirebaseAuth.instance;
bool isLoggedIn() {
return auth.currentUser != null;
}
String? userId() {
return auth.currentUser?.uid;
}
String? email() {
return auth.currentUser?.email;
}
void signup(String email, String password) async {
try {
await auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) => {writedDetailsToFirestore()})
.catchError((e) {
Fluttertoast.showToast(msg: e!.message);
});
notifyListeners();
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
if (kDebugMode) {
print('The password provided is too weak.');
}
} else if (e.code == 'email-already-in-use') {
if (kDebugMode) {
print('The account already exists for that email.');
}
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
}
void login(String email, String password) async {
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
notifyListeners();
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
if (kDebugMode) {
print('The password provided is too weak.');
}
} else if (e.code == 'email-already-in-use') {
if (kDebugMode) {
print('The account already exists for that email.');
}
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
}
void logout() async {
await auth.signOut();
notifyListeners();
}
}
this is how the screen code look likes, I repeated myself because i wanted it to appear as a single block though it feels like out doing myself.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
class RegisterScreen extends StatefulWidget {
const RegisterScreen({Key? key}) : super(key: key);
@override
State<RegisterScreen> createState() => _RegisterScreenState();
}
class _RegisterScreenState extends State<RegisterScreen> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _confirmController = TextEditingController();
final TextEditingController _userNameController = TextEditingController();
final formkeyOnRegister = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
final userDao = Provider.of<UserDao>(context, listen: false);
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.all(10),
child: Form(
key: formkeyOnRegister,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
height: 300,
child: Image.asset('assets/logo.png'),
),
const SizedBox(
height: 20,
),
TextFormField(
textCapitalization: TextCapitalization.none,
autofocus: false,
controller: _userNameController,
obscureText: false,
onSaved: (value) {
_userNameController.text = value!;
},
validator: (value) {
if (value!.isEmpty) {
return 'Please fill in Username';
}
{
return null;
}
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(CupertinoIcons.person),
labelText: 'Username',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
TextFormField(
autofocus: false,
textCapitalization: TextCapitalization.none,
controller: _emailController,
onSaved: (value) {
_emailController.text = value!;
},
validator: (value) {
if (value!.isEmpty) {
return 'Email is empty';
}
if (!RegExp(
r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))
)
.hasMatch(value)) {
'Please enter valid email';
}
{
return null;
}
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(Icons.email_outlined),
labelText: 'Email',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
//Password field
TextFormField(
textCapitalization: TextCapitalization.none,
autofocus: false,
controller: _passwordController,
obscureText: true,
onSaved: (value) {
_passwordController.text = value!;
},
validator: (value) {
RegExp regex = RegExp(r'^.{6,}
);
if (value!.isEmpty) {
return ("Password is required");
}
if (!regex.hasMatch(value)) {
return ("Enter Valid Password(Min. 6 Characters");
}
return null;
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(CupertinoIcons.lock),
labelText: 'Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
// confirm password
TextFormField(
textCapitalization: TextCapitalization.none,
autofocus: false,
controller: _confirmController,
obscureText: true,
onSaved: (value) {
_passwordController.text = value!;
},
validator: (value) {
if (_confirmController.text !=
_passwordController.text) {
return "Password don't match";
}
return null;
},
style: const TextStyle(fontSize: 20),
decoration: InputDecoration(
contentPadding: const EdgeInsets.all(10),
prefixIcon: const Icon(CupertinoIcons.lock),
labelText: 'Confirm Password',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(18))),
),
const SizedBox(
height: 20,
),
Material(
borderRadius: BorderRadius.circular(30),
color: const Color.fromARGB(255, 207, 19, 5),
child: MaterialButton(
onPressed: () {
userDao.signup(_emailController.text,
_passwordController.text);
},
minWidth: MediaQuery.of(context).size.width * 0.5,
child: const Text(
'REGISTER',
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontWeight: FontWeight.w600),
)),
),
const SizedBox(
height: 20,
),
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
"I already have an account. ",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w200),
),
GestureDetector(
onTap: () {
Navigator.pushReplacementNamed(
context, "login");
},
child: const Text(
"LOGIN",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w200,
color: Color.fromARGB(255, 207, 19, 5),
),
))
],
),
)
],
)),
),
),
),
);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论