在我的代码中,用户是通过电话身份验证登录。登录后,我想获取用户的用户ID,并将其及其个人详细信息添加到Firebase数据库中。
但是,当我这样做时,数据库中的路径是直接的,而不是应该通过第一个UserId然后在其下的个人详细信息。
我还提供了带有数据库输出的图像。
码:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:udharibook/Screens/SignInPage.dart';
import 'package:udharibook/Screens/dashboard.dart';

class AuthService  {
  String UserId ='';
  final DBRef = FirebaseDatabase.instance.reference().child('Users');
  final FirebaseAuth _auth = FirebaseAuth.instance;
  handleAuth(){
    return StreamBuilder(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (BuildContext, snapshot){
        if(snapshot.hasData){
          getCurrentUser();
          writeData();
          return DashboardPage();
        }
        else {
          return SignIn();
        }
      },
    );
  }
  getCurrentUser() async{
    final FirebaseUser user = await _auth.currentUser();
    final uid = user.uid;
    // Similarly we can get email as well
    //final uemail = user.email;
    UserId = uid;
    print('User ID:  '+UserId);

    //print(uemail);
  }

  void writeData(){
    DBRef.child(UserId).set({
      'id':'ID1',
      'Name':'Mehul Jain',
      'Phone':'8856061841'
    });
  }

  signOut(){
    FirebaseAuth.instance.signOut();
  }

  signIn(AuthCredential authCreds){
    FirebaseAuth.instance.signInWithCredential(authCreds);
  }

  signInWithOTP(smsCode,verId){
    AuthCredential authCreds = PhoneAuthProvider.getCredential(
        verificationId: verId,
        smsCode: smsCode
    );
    signIn(authCreds);
  }
}

数据库镜像firebase - 在Flutter中将数据保存到Firebase实时数据库-LMLPHP

最佳答案

请尝试以下操作:

  void writeData() async{
    final FirebaseUser user = await _auth.currentUser();
    final uid = user.uid;
    DBRef.child(uid).set({
      'id':'ID1',
      'Name':'Mehul Jain',
      'Phone':'8856061841'
    });
  }
删除getCurrentUser()方法并在uid中检索writeData()

10-05 20:54
查看更多