【问题标题】:Flutter link firebase auth User UID to cloud_firestoreFlutter 将 firebase auth 用户 UID 链接到 cloud_firestore
【发布时间】:2022-01-09 11:50:00
【问题描述】:

编辑:我创建了一个新的 dartfile adduser。

import 'package:cloud_firestore/cloud_firestore.dart';

FirebaseFirestore firestore = FirebaseFirestore.instance;

class DatabaseService {

  final String uid;
  DatabaseService({ required this.uid });

  // collection reference
  final CollectionReference userCollection = FirebaseFirestore.instance.collection('users');

  Future updateUserData(String ouderName, String kindName, String school,) async {
    return await userCollection.doc(uid).set({
      'ouderName' : ouderName,
      'kindName' : kindName,
      'school' : school,
    });
  }
}

我在返回用户之前在 fire_auth.dart 中添加了这行代码。

await DatabaseService(uid: user!.uid).updateUserData('', '', '');

现在似乎工作正常,来自身份验证的 uid 正在转移到用户集合中的文档。

原问题: 我在注册后将 firebase auth 连接到 firestore 时遇到问题。我正在使用电子邮件和密码注册。此时,当用户注册时,正在 Firebase Authentication 中制作 UID。我想要的是这个 UID 用于在 cloud firestore 中创建一个新的用户集合。我怎样才能做到这一点? 新用户在主应用时可以写入额外的数据,所以我只想在注册后捕获这个UID。

任何帮助将不胜感激。

这是注册页面的代码:

import 'package:flutter/material.dart';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:planplay/login/profile_page.dart';
import 'package:planplay/login/fire_auth.dart';
import 'package:planplay/login/validator.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _registerFormKey = GlobalKey<FormState>();

  final _nameTextController = TextEditingController();
  final _emailTextController = TextEditingController();
  final _passwordTextController = TextEditingController();

  final _focusName = FocusNode();
  final _focusEmail = FocusNode();
  final _focusPassword = FocusNode();

  bool _isProcessing = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _focusName.unfocus();
        _focusEmail.unfocus();
        _focusPassword.unfocus();
      },
      child: Scaffold(
        appBar: AppBar(
          iconTheme: IconThemeData(color: Color.fromRGBO(132, 76, 130, 1)),
          title: Text('Registreren',
              style: TextStyle(color: Color.fromRGBO(132, 76, 130, 1))),
          centerTitle: true,
          backgroundColor: Color.fromRGBO(250, 202, 48, 1),
        ),
        body: Center(
    child: SingleChildScrollView(
    reverse: true,
    padding: EdgeInsets.all(32),
    child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 120.0,
                  width: 120.0,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                          'assets/images/logo.jpg'),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                SizedBox(height: 24.0),
                Form(
                  key: _registerFormKey,
                  child: Column(
                    children: <Widget>[
                      TextFormField(
                        controller: _nameTextController,
                        focusNode: _focusName,
                        validator: (value) => Validator.validateName(
                          name: value,
                        ),
                    decoration: InputDecoration(
                      enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color:Color.fromRGBO(132, 76, 130, 1))),
                      hintText: "Naam ouder",
                      hintStyle: TextStyle(color: Color.fromRGBO(132, 76, 130, 1)),
                      focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Color.fromRGBO(250, 202, 48, 1))),
                          errorBorder: UnderlineInputBorder(
                            borderRadius: BorderRadius.circular(6.0),
                            borderSide: BorderSide(
                              color: Colors.red,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 16.0),
                      TextFormField(
                        controller: _emailTextController,
                        focusNode: _focusEmail,
                        validator: (value) => Validator.validateEmail(
                          email: value,
                        ),
                        decoration: InputDecoration(
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color:Color.fromRGBO(132, 76, 130, 1))),
                          hintText: "Email adres",
                          hintStyle: TextStyle(color: Color.fromRGBO(132, 76, 130, 1)),
                          focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: Color.fromRGBO(250, 202, 48, 1))),
                          errorBorder: UnderlineInputBorder(
                            borderRadius: BorderRadius.circular(6.0),
                            borderSide: BorderSide(
                              color: Colors.red,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 16.0),
                      TextFormField(
                        controller: _passwordTextController,
                        focusNode: _focusPassword,
                        obscureText: true,
                        validator: (value) => Validator.validatePassword(
                          password: value,
                        ),
                        decoration: InputDecoration(
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color:Color.fromRGBO(132, 76, 130, 1))),
                          hintText: "Wachtwoord",
                          hintStyle: TextStyle(color: Color.fromRGBO(132, 76, 130, 1)),
                          focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(color: Color.fromRGBO(250, 202, 48, 1))),
                          errorBorder: UnderlineInputBorder(
                            borderRadius: BorderRadius.circular(6.0),
                            borderSide: BorderSide(
                              color: Colors.red,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 32.0),
                      _isProcessing
                          ? CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Color.fromRGBO(250, 202, 48, 1)),
                                              )
                          : Row(
                        children: [
                          Expanded(
                            child: ElevatedButton(
                              onPressed: () async {
                                setState(() {
                                  _isProcessing = true;
                                });

                                if (_registerFormKey.currentState!
                                    .validate()) {
                                  User? user = await FireAuth
                                      .registerUsingEmailPassword(
                                    name: _nameTextController.text,
                                    email: _emailTextController.text,
                                    password:
                                    _passwordTextController.text,
                                  );

                                  setState(() {
                                    _isProcessing = false;
                                  });


                                  if (user != null) {
                                    Navigator.of(context)
                                        .pushAndRemoveUntil(
                                      MaterialPageRoute(
                                        builder: (context) =>
                                            ProfilePage(user: user),
                                      ),
                                      ModalRoute.withName('/'),
                                    );
                                  }
                                }
                                else {
                                  final snackBar = SnackBar(content: Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Icon(Icons.error_outline, size: 32, color:Color.fromRGBO(132, 76, 130, 1)),
                                      const SizedBox(width: 16),
                                      Expanded(child: Text('Gegevens onjuist, vul de juiste gegevens in',
                                          style: TextStyle(color:Color.fromRGBO(132, 76, 130, 1))),
                                      ),
                                    ],
                                  ),
                                    backgroundColor: Colors.red,
                                  );

                                  ScaffoldMessenger.of(context).showSnackBar(snackBar);
                                  setState(() {
                                    _isProcessing = false;
                                  });
                                }
                              },
                              child: Text(
                                'Registreren',
                                style: TextStyle(color: Color.fromRGBO(132, 76, 130, 1)),
                              ),
                                style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(Color.fromRGBO(250, 202, 48, 1)),
                                ),
                              ),
                            ),
                        ],
                      )
                    ],
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    ),
    ),
    );
  }
}

【问题讨论】:

  • 您没有在您共享的代码中的任何地方调用 Firestore,因此我们很难比@cheese.tea 下面链接的文档提供更好的帮助。我建议您尝试自己构建必要的代码,如果遇到问题,请在此处回复。

标签: flutter google-cloud-firestore firebase-authentication


【解决方案1】:

不确定您是否检查过有关这方面的 flutterfire 文档,但这里是链接:https://firebase.flutter.dev/docs/firestore/usage

无论如何,这里有一个小部件,您可以尝试一下。

final FirebaseFirestore _firestoreDb = FirebaseFirestore.instance;
final User _firebaseUser = FirebaseAuth.Instance.currentUser;


 void _createUserInFirestore(User _firebaseUser) {
    _firestoreDb.doc('/users/${_firebaseUser.uid}'));
    update();
  }

【讨论】:

    猜你喜欢
    • 2016-11-01
    • 2017-10-06
    • 1970-01-01
    • 2020-10-10
    • 2020-01-01
    • 2019-03-19
    • 2020-11-14
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多