简体   繁体   English

Flutter 注册问题

[英]Flutter Sign up Issue

I am facing issue to register a user.我在注册用户时遇到问题。 At first time it registered the user but didn't store attributes to database on firebase.第一次它注册了用户,但没有将属性存储到 firebase 上的数据库中。 Now it neither registering any user .现在它既不注册任何用户。 register button show nothing on pressing.注册按钮按下时不显示任何内容。

This is my Flutter Doctor这是我的 Flutter 医生

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.18363.657], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[√] Android Studio (version 3.6)
[!] VS Code (version 1.42.1)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (1 available)

! Doctor found issues in 1 category.

Errors:错误:

Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device Android SDK built for x86...
W/ad.meds_at_hom(19354): Verification of java.security.PublicKey com.android.org.conscrypt.OpenSSLKey.getPublicKey() took 107.202ms
I/ad.meds_at_hom(19354): Background young concurrent copying GC freed 12933(787KB) AllocSpace objects, 10(344KB) LOS objects, 28% free, 2334KB/3266KB, paused 634us total 358.299ms
D/EGL_emulation(19354): eglMakeCurrent: 0xdeb3d9c0: ver 2 0 (tinfo 0xdebe7bc0)
I/OpenGLRenderer(19354): Davey! duration=2050ms; Flags=1, IntendedVsync=54921730240636, Vsync=54921730240636, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=54921742554500, AnimationStart=54921742628900, PerformTraversalsStart=54921742683700, DrawStart=54923608726000, SyncQueued=54923631845100, SyncStart=54923669426300, IssueDrawCommandsStart=54923670823500, SwapBuffers=54923716835000, FrameCompleted=54923818262600, DequeueBufferDuration=24903000, QueueBufferDuration=1432000, 
I/Choreographer(19354): Skipped 124 frames!  The application may be doing too much work on its main thread.
D/EGL_emulation(19354): eglMakeCurrent: 0xe967e7a0: ver 2 0 (tinfo 0xd2995d80)
I/ad.meds_at_hom(19354): Background young concurrent copying GC freed 10059(595KB) AllocSpace objects, 0(0B) LOS objects, 30% free, 2271KB/3266KB, paused 538us total 148.169ms
W/IInputConnectionWrapper(19354): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(19354): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(19354): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(19354): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(19354): getTextAfterCursor on inactive InputConnection

This is SignUp code:这是注册代码:

import 'package:firebase_auth/firebase_auth.dart';


import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:meds_at_home/pages/home.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import '../db/users.dart';

class SignUp extends StatefulWidget {
  @override
  _SignUpState createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  final _formKey = GlobalKey<FormState>();
  UserServices _userServices = UserServices();
  TextEditingController _email = TextEditingController();
  TextEditingController _password = TextEditingController();
  TextEditingController _name = TextEditingController();
  TextEditingController _confirmPassword = TextEditingController();
  String gender;
  String groupvalue = "Male";
  bool hidePass = true;
  bool hidePass1 = true;
  bool loading = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(children: <Widget>[
        Image.asset(
          'images/back1.webp',
          fit: BoxFit.fill,
          width: double.infinity,
          height: double.infinity,
        ),
//            Container(
//              alignment: Alignment.topRight,
//              child: Image.asset('images/logo.png'),
//              width: 240.0,
//              height: 200.0,
//            ),
        Container(
          color: Colors.black12.withOpacity(0.4),
          width: double.infinity,
          height: double.infinity,
        ),
        Center(
          child: Padding(
            padding: const EdgeInsets.only(top: 150.0),
            child: Center(
              child: Form(
                  key: _formKey,
                  child: ListView(
                    children: <Widget>[
                      Padding(
                        padding:
                            const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: TextFormField(
                              controller: _name,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Full Name",
                                icon: Icon(Icons.person),
                              ),
                              validator: (value) {
                                if (value.isEmpty) {
                                  return "The name field cannot be empty";
                                }
                                return null;
                              },
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                            const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: new Container(
                          color: Colors.white.withOpacity(0.2),
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                  child: ListTile(
                                title: Text(
                                  "Male",
                                  textAlign: TextAlign.end,
                                  style: TextStyle(color: Colors.white),
                                ),
                                trailing: Radio(
                                    value: "Male",
                                    groupValue: groupvalue,
                                    onChanged: (e) => valueChanged(e)),
                              )),
                              Expanded(
                                  child: ListTile(
                                title: Text(
                                  "Female",
                                  textAlign: TextAlign.end,
                                  style: TextStyle(color: Colors.white),
                                ),
                                trailing: Radio(
                                    value: "Female",
                                    groupValue: groupvalue,
                                    onChanged: (e) => valueChanged(e)),
                              )),
                            ],
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                            const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: TextFormField(
                              controller: _email,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                                hintText: "Email",
                                icon: Icon(Icons.email),
                              ),
                              // ignore: missing_return
                              validator: (value) {
                                if (value.isEmpty) {
                                  Pattern pattern =
                                      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,}))$';
                                  RegExp regex = new RegExp(pattern);
                                  if (!regex.hasMatch(value))
                                    return 'Please make sure your email address is valid';
                                  else
                                    return null;
                                }
                              },
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                            const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: ListTile(
                              title: TextFormField(
                                controller: _password,
                                obscureText: hidePass,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: "Password",
                                  icon: Icon(Icons.lock_outline),
                                ),
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return "The password field cannot be empty";
                                  } else if (value.length < 6) {
                                    return "The password should have  at least 6 characters ";
                                  }
                                  return null;
                                },
                              ),
                              trailing: IconButton(
                                  icon: Icon(Icons.remove_red_eye),
                                  onPressed: () {
                                    setState(() {
                                      if (hidePass == false) {
                                        hidePass = true;
                                      } else {
                                        hidePass = false;
                                      }
                                    });
                                  }),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                            const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                          borderRadius: BorderRadius.circular(10.0),
                          color: Colors.white.withOpacity(0.8),
                          elevation: 0.0,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 12.0),
                            child: ListTile(
                              title: TextFormField(
                                controller: _confirmPassword,
                                obscureText: hidePass1,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: "Confirm Password",
                                  icon: Icon(Icons.lock_outline),
                                ),
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return "The password field cannot be empty";
                                  } else if (value.length < 6) {
                                    return "The password should have  at least 6 characters";
                                  } else if (_password.text != value) {
                                    return "Password Don't match";
                                  }

                                    return null;
                                },
                              ),
                              trailing: IconButton(
                                  icon: Icon(Icons.remove_red_eye),
                                  onPressed: () {
                                    setState(() {
                                      if (hidePass1 == false) {
                                        hidePass1 = true;
                                      } else {
                                        hidePass1 = false;
                                      }
                                    });
                                  }),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding:
                            const EdgeInsets.fromLTRB(14.0, 4.0, 14.0, 4.0),
                        child: Material(
                            borderRadius: BorderRadius.circular(20.0),
                            color: Colors.blueAccent,
                            elevation: 0.0,
                            child: MaterialButton(
                              onPressed: () async {
                                formValidate();
                              },
//                  async{
//                    if(_formKey.currentState.validate()){
//                      if(!await user.signIn(_email.text, _password.text))
//                        _key.currentState.showSnackBar(SnackBar(content: Text("Sign in failed")));
//                    }
//                  },
                              minWidth: MediaQuery.of(context).size.width,
                              child: Text(
                                "Register",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 20.0),
                              ),
                            )),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          Padding(
                              padding: const EdgeInsets.all(6.0),
                              child: InkWell(
                                  onTap: () {
                                    Navigator.pop(context);
                                  },
                                  child: Text(
                                    "I already have an account",
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16),
                                  ))),
                        ],
                      ),
                    ],
                  )),
            ),
          ),
        ),

        Visibility(
            visible: loading ?? true,
            child: Center(
              child: Container(
                alignment: Alignment.center,
                color: Colors.white.withOpacity(0.2),
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.blueAccent),
                ),
              ),
            )),
      ]),

//
    );
  }

  valueChanged(e) {
    setState(() {
      if (e == "Male") {
        groupvalue = e;
        gender = e;
      } else if (e == "Female") {
        groupvalue = e;
        gender = e;
      }
    });
  }

  Future formValidate() async {
    FormState formState = _formKey.currentState ;
    formState.reset();
    if(formState.validate()){

      FirebaseUser user =  await firebaseAuth.currentUser() ;
      if (user == null) {

         firebaseAuth
            .createUserWithEmailAndPassword(
                email: _email.text, password: _password.text)
            .then((user) => {
                  _userServices.createUser(
                    user.uid,
                      {
                    "username": user..displayName ,
                    "email": user.email,
                    "userId": user.uid,
                    "gender": gender,
                   // "Password": ,
                  })
                })
            .catchError((err) => {print(err.toString())});
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => HomePage()));
      }
    }
  }
}

this is DB/users.dart这是 DB/users.dart

import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_auth/firebase_auth.dart';

class UserServices {
  FirebaseDatabase _database = FirebaseDatabase.instance;
  String ref = "users";

  createUser(String uid ,Map value) {
    _database
        .reference()
        .child("$ref/$uid")
        .set(value)
        .catchError((e) => {print(e.toString())});
  }
}

you are resetting form before validating and before getting value from your form, so you should reset your form after creating user.您在验证之前和从表单中获取价值之前重置表单,因此您应该在创建用户后重置表单。

Future formValidate() async {
FormState formState = _formKey.currentState ;
if(formState.validate()){

  FirebaseUser user =  await firebaseAuth.currentUser() ;
  if (user == null) {

     firebaseAuth
        .createUserWithEmailAndPassword(
            email: _email.text, password: _password.text)
        .then((user) => {
              _userServices.createUser(
                user.uid,
                  {
                "username": user..displayName ,
                "email": user.email,
                "userId": user.uid,
                "gender": gender,
               // "Password": ,
              })
            })
        .catchError((err) => {print(err.toString())});

     formState.reset(); // replace from top to here

    Navigator.pushReplacement(
        context, MaterialPageRoute(builder: (context) => HomePage()));
    }
  }
}

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

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