'Flutter, provider and firebase

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),
                               ),
                             ))
                       ],
                     ),
                   )
                 ],
               )),
         ),
       ),
     ),
   );
 }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source