简体   繁体   中英

User registration and authentication in flutter

When user registration, authentication occurred but not added data to the firebase that asking while signup such as registration number, Name, and TP no, etc. in flutter. So, what's wrong with my code?

Below one is the code for signup_view.dart file

import 'package:auto_size_text/auto_size_text.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:uocportal/provider_widget.dart';
import 'package:uocportal/auth_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
//import 'package:auto_size_text/auto_size_text.dart';

enum AuthFormType { signIn, signUp, reset }

class SignUpView extends StatefulWidget {
  final AuthFormType authFormType;

  SignUpView({Key key, @required this.authFormType}) : super(key: key);

  @override
  _SignUpViewState createState() =>
      _SignUpViewState(authFormType: this.authFormType);
}


class _SignUpViewState extends State<SignUpView> {
  AuthFormType authFormType;
  _SignUpViewState({this.authFormType});

  var reNumFieldController = new TextEditingController();

  final formKey = GlobalKey<FormState>();
  String
      _email,
      _password,
      _name,
      _regnumber,
      _faculty,
      _contact,
      _warning;


  final _userCollectionReference = Firestore.instance;
 // prefs.setString('stringRegnumValue', _regnumber);

  Future createUser() async {

    try {

       final prefs = await SharedPreferences.getInstance();
       prefs.setString('my_regno_key', _regnumber.toString());

      await _userCollectionReference
          .collection('Users')
          .document()
          .setData({
        'username': _name,
        'email': _email,
        'contact': _contact,
        'faculty': _faculty,
        'regnumber': _regnumber
      });

    } catch (e) {
      return e.message;
    }
  }

  void switchFormState(String state) {
    formKey.currentState.reset();
    if (state == "signUp") {
      setState(() {
        authFormType = AuthFormType.signUp;
      });
    } else {
      setState(() {
        authFormType = AuthFormType.signIn;
      });
    }
  }

  bool validate() {
    final form = formKey.currentState;
    form.save();
    if (form.validate()) {
      form.save();
      return true;
    } else {
      return false;
    }
  }

  void submit() async {
    if (validate()) {
      try {
        final auth = Provider.of(context).auth;
        if (authFormType == AuthFormType.signIn) {
          String uid = await auth.signinWithEmailAndPassword(_email, _password);
          print("$uid");
          Navigator.of(context).pushReplacementNamed('/home');
        } else if (authFormType == AuthFormType.reset) {
          await auth.sendPasswordResetEmail(_email);
          print("password reset mail sent");
          _warning = "A Password reset link has been sent to $_email";
          setState(() {
            authFormType = AuthFormType.signIn;
          });
        } else {
          String uid = await auth.createUserWithEmailAndPassword(
              _email, _password, _name, _regnumber, _faculty, _contact);
          print("$uid");
          Navigator.of(context).pushReplacementNamed('/home');
          createUser();
        }
      } catch (e) {
        print(e);
        // setState(() {
        _warning = e.message;
        //  });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final _height = MediaQuery.of(context).size.height;
    final _width = MediaQuery.of(context).size.width;

    return Scaffold(
        appBar: AppBar(
          title: Text('UOC Portal'),
          backgroundColor: Color(0xFF4A184C),
        ),
        body: new GestureDetector(
            onTap: () {
              // call this method here to hide soft keyboard
              FocusScope.of(context).requestFocus(new FocusNode());
            },
            child: Container(
              color: Colors.white,
              height: _height,
              width: _width,
              child: SingleChildScrollView(
                child: Container(
                  child: Column(
                    children: <Widget>[
                      showAlert(),
                      SizedBox(
                        height: _height * 0.05,
                      ),
                      buildHeaderText(),
                      buildSubHeadText(),
                      SizedBox(
                        height: _height * 0.02,
                      ),
                      Padding(
                        padding: const EdgeInsets.all(10.0),
                        child: Form(
                            key: formKey,
                            child: Column(
                                children: buildInputs() + buildButtons())),
                      )
                    ],
                  ),
                ),
              ),
            )));
  }

  Widget showAlert() {
    if (_warning != null) {
      return Container(
        color: Colors.amber,
        width: double.infinity,
        padding: EdgeInsets.all(8.0),
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Icon(Icons.error_outline),
            ),
            Expanded(
                child: AutoSizeText(
              _warning,
              maxLines: 3,
            )),
            IconButton(
                icon: Icon(Icons.close),
                onPressed: () {
                  setState(() {
                    _warning = null;
                  });
                })
          ],
        ),
      );
    }
    return SizedBox(
      height: 0,
    );
  }

  AutoSizeText buildHeaderText() {
    String _headerText;
    if (authFormType == AuthFormType.signIn) {
      _headerText = "Welcome !!";
    } else if (authFormType == AuthFormType.reset) {
      _headerText = "Reset Password";
    } else {
      _headerText = "Sign Up";
    }
    return AutoSizeText(
      _headerText,
      maxLines: 2,
      textAlign: TextAlign.center,
      style: TextStyle(
          fontSize: 35, color: Color(0xFF4A184C), fontWeight: FontWeight.bold),
    );
  }

  AutoSizeText buildSubHeadText() {
    String _headerText;
    if (authFormType == AuthFormType.signIn) {
      _headerText = "Sign in to Continue";
    } else if (authFormType == AuthFormType.reset) {
      _headerText = "";
    } else {
      _headerText = "Create a new Account";
    }
    return AutoSizeText(
      _headerText,
      maxLines: 2,
      textAlign: TextAlign.center,
      style: TextStyle(fontSize: 15, color: Color(0xFF4A184C)),
    );
  }

  List<Widget> buildInputs() {
    List<Widget> textFields = [];

    if (authFormType == AuthFormType.reset) {
      textFields.add(
        TextFormField(
          keyboardType: TextInputType.text,
          validator: EmailValidator.validate,
          style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
          decoration: buildSignUpInputDecoration("Email"),
          onSaved: (value) => _email = value,
        ),
      );
      textFields.add(SizedBox(
        height: 8,
      ));

      return textFields;
    }

    //if were in the signup state add name
    if (authFormType == AuthFormType.signUp) {
      textFields.add(
        TextFormField(
          keyboardType: TextInputType.text,
          validator: NameValidator.validate,
          style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
          decoration: buildSignUpInputDecoration("Name"),
          onSaved: (value) => _name = value,
        ),
      );

      textFields.add(SizedBox(
        height: 8,
      ));

      textFields.add(
        DropdownButtonFormField<String>(
          validator:(value) {
            if (value == null) {
              return "Faculty can't be empty";
            }
          },

          value: _faculty,
          items: ["Science",
          "Management",
            "Law",
            "Art",
            "UCSC",
            "Medicine",
            "Technology",
            "Nursing",
            "IIM"
          ].map((label) => DropdownMenuItem(
            child: Text(label),
            value: label,
          ))
          .toList(),
          onChanged: (value) {
            setState(() => _faculty = value);
          },

          style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
          decoration: buildSignUpInputDecoration("Faculty"),
        ),
      );

      textFields.add(SizedBox(
        height: 8,
      ));

      textFields.add(
        TextFormField(
          validator: RegNoValidator.validate,
          style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
          decoration: buildSignUpInputDecoration("Registration No."),
          controller: reNumFieldController,
          onSaved: (value) => _regnumber = value,
        ),
      );

      textFields.add(SizedBox(
        height: 8,
      ));

      textFields.add(
        TextFormField(
          keyboardType: TextInputType.phone,
          validator: ContactValidator.validate,
          style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
          decoration: buildSignUpInputDecoration("Contact Number"),
          onSaved: (value) => _contact = value,
        ),
      );

      textFields.add(SizedBox(
        height: 8,
      ));
    }

    //add email and Password
    textFields.add(
      TextFormField(
        keyboardType: TextInputType.emailAddress,
        validator: EmailValidator.validate,
        style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
        decoration: buildSignUpInputDecoration("Email"),
        onSaved: (value) => _email = value,
      ),
    );

    textFields.add(SizedBox(
      height: 8,
    ));

    textFields.add(
      TextFormField(
        validator: PasswordValidator.validate,
        style: TextStyle(fontSize: 18.0, color: Color(0xFF4A184C)),
        decoration: buildSignUpInputDecoration("Password"),
        obscureText: true,
        onSaved: (value) => _password = value,
      ),
    );

    return textFields;
  }

  InputDecoration buildSignUpInputDecoration(String hint) {
    return InputDecoration(
      //hintText: hint,
      fillColor: Colors.white,
      filled: true,
      focusColor: Colors.amber,
      labelText: hint,
      errorMaxLines: 1,
      hintStyle:
          TextStyle(color: Color(0xFF4A184C), fontWeight: FontWeight.bold),
      labelStyle:
          TextStyle(color: Color(0xFF4A184C), fontWeight: FontWeight.bold),
      enabledBorder: OutlineInputBorder(
          borderSide: const BorderSide(color: Colors.amber),
          borderRadius: new BorderRadius.circular(25.0)),
      contentPadding:
          const EdgeInsets.only(left: 14.0, bottom: 10.0, top: 10.0),
    );
  }

  List<Widget> buildButtons() {
    String _switchButton, _newFormState, _submitButtonText;
    bool _showForgotPasowrd = false;
    if (authFormType == AuthFormType.signIn) {
      _switchButton = "Don't have an account? | Sign Up";
      _newFormState = "signUp";
      _submitButtonText = "Sign In";
      _showForgotPasowrd = true;
    } else if (authFormType == AuthFormType.reset) {
      _switchButton = "Return to Sign In";
      _newFormState = "signIn";
      _submitButtonText = "Submit";
      _showForgotPasowrd = false;
    } else {
      _switchButton = "Have an Account? Sign In";
      _newFormState = "signIn";
      _submitButtonText = "Sign Up";
    }

    return [
      SizedBox(
        height: 10,
      ),
      Container(
        width: MediaQuery.of(context).size.width * 0.7,
        child: RaisedButton(
            onPressed: () {
              submit();
            },
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30.0)),
            color: Color(0xFF4A184C),
            textColor: Colors.amber,
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text(
                _submitButtonText,
                style: TextStyle(fontSize: 20),
              ),
            )),
      ),
      showForgotPassowrd(_showForgotPasowrd),
      FlatButton(
          onPressed: () {
            switchFormState(_newFormState);
          },
          child: Text(
            _switchButton,
            style: TextStyle(color: Colors.amber),
          )),
    ];
  }

  Widget showForgotPassowrd(bool visibale) {
    return Visibility(
      child: FlatButton(
          onPressed: () {
            setState(() {
              authFormType = AuthFormType.reset;
            });
          },
          child: Text(
            "Forgot Password?",
            style: TextStyle(color: Colors.amber),
          )),
      visible: visibale,
    );
  }
}

Below one is the code for auth_service.dart file

import 'package:firebase_auth/firebase_auth.dart';


class AuthService {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;


  Stream<String> get onAuthStateChanged => _firebaseAuth.onAuthStateChanged.map(
    (FirebaseUser user )=> user?.uid,
  );

  //Email & Password Sign Up
  Future <String> createUserWithEmailAndPassword(String email, String password, 
  String name, String regnumber, String faculty, String contact) async {
      final currentUser = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password,);



        //update the username
        var userUpdateInfo = UserUpdateInfo();
        userUpdateInfo.displayName = name;
        await currentUser.updateProfile(userUpdateInfo);
        await currentUser.reload();
        return currentUser.uid;

  }

  //Email & Password Sign In
  Future <String> signinWithEmailAndPassword(String email, String password) async{
    return (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)).uid;
  }

  //Sign Out
  signOut(){
    return _firebaseAuth.signOut();
  }

  //reset password
  Future sendPasswordResetEmail(String email) async {
    return _firebaseAuth.sendPasswordResetEmail(email: email);
  }

}

These are the codes that I've used for creating user registration, sign-in, and reset the password. Here sign-in, sign-up and password reset appear within one page according to its state. Please give me a better soution for this. :)

You'd need to execute createUser() before navigating to a different screen. It's best to add debugPrint() on the requests to be executed to verify that they're being called as expected.

Then update user data.

CollectionReference _userCollectionReference = FirebaseFirestore.instance
    .collection('Users');
var userDocData = new Map<String, dynamic>();
userDocData['username'] = _name;
userDocData['email'] = _email;
userDocData['contact'] = _contact;
userDocData['faculty'] = _faculty;
userDocData['regnumber'] = _regnumber;
await _userCollectionReference.add(userDocData);

Also, make sure that the rules ables users to write to Firestore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM