简体   繁体   English

flutter中的用户注册和认证

[英]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.用户注册时,进行了认证,但没有向firebase中添加数据,注册时询问flutter中的注册号、姓名和TP号等。 So, what's wrong with my code?那么,我的代码有什么问题?

Below one is the code for signup_view.dart file下面是signup_view.dart文件的代码

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下面是auth_service.dart文件的代码

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.此处登录、注册和密码重置根据其 state 显示在一页内。 Please give me a better soution for this.请给我一个更好的解决方案。 :) :)

You'd need to execute createUser() before navigating to a different screen.在导航到不同的屏幕之前,您需要执行createUser() It's best to add debugPrint() on the requests to be executed to verify that they're being called as expected.最好在要执行的请求上添加debugPrint()以验证它们是否按预期被调用。

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.此外,请确保规则允许用户写入 Firestore。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Firebase 用户注册/用户名身份验证 - Firebase User Registration / Authentication with Username Flutter用户注册存储数据 - Flutter user registration storing data 使用Firebase进行Flutter用户注册:添加额外的用户信息(年龄,用户名) - Flutter user registration with Firebase: Add extra user information (age, username) Flutter 中的 Firebase 身份验证检查用户是否是新用户 - Firebase Authentication in Flutter Check if user is a new user 如何在flutter中成功检测firebase用户注册和登录 - How to detect firebase user registration and signIn successfully in flutter 在确认注册之前验证用户的电子邮件地址,使用 Flutter 和 Firebase - Verify a user's email address before confirming registration, with Flutter and Firebase 在 Flutter 中使用 FirebaseAuth 检查用户的身份验证状态 - check authentication state of User using FirebaseAuth in Flutter 在 Flutter 中使用 Firebase 身份验证检查用户是否是新用户 - Check if user is new using Firebase Authentication in Flutter Flutter | Firebase 用户身份验证和配置文件创建 - Flutter | Firebase User Authentication & Profile creation 如何使用 Firebase 身份验证在 Flutter 中注销用户 - How to Signout a user in Flutter with Firebase authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM