Flutter、Provider 和 Firebase

发布于 2025-01-13 16:46:45 字数 10687 浏览 2 评论 0原文

我正在编写代码以使用提供程序包和 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文