M J
M J

Reputation: 83

Save Data to Firebase Realtime Database in Flutter

In my code the user is Sign in through phone authentication.After login i want to get the user id of the user and add it to the Firebase database along with its personal details.

But when i have done this the Path in database is direct rather than it should be via first UserId then under that the personal details. I have also provide the image with the database output.

Code:

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);
  }
}
 

Database Image enter image description here

Upvotes: 1

Views: 5667

Answers (2)

Sumeet.Jain
Sumeet.Jain

Reputation: 1609

getCurrentUser() method is an async method, so it not sure that your userId will be having value before the writeData() method is called.

so what you can do is call writeData() after completion of getCurrentUser() method i.e. :

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();
          //call writeData() from inside the above method
          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);
    
    //Here you add the method calling 
    writeData();
  }

  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);
  }
}

Upvotes: 3

Peter Haddad
Peter Haddad

Reputation: 80944

Try the following:

  void writeData() async{
    final FirebaseUser user = await _auth.currentUser();
    final uid = user.uid;
    DBRef.child(uid).set({
      'id':'ID1',
      'Name':'Mehul Jain',
      'Phone':'8856061841'
    });
  }

Remove the getCurrentUser() method and retrieve the uid in writeData()

Upvotes: 4

Related Questions