Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to flutter and in my below code there is read data function is called at line 18(it performs Firebase Database operations) I want that the readData() function must complete its execution before going to the print statement(line 19) and further execution.


What I have tried:

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/UserProfile.dart';
import 'package:udharibook/Screens/dashboard.dart';

class AuthService  {
  bool flag = false;
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final DBRef = FirebaseDatabase.instance.reference().child('Users');

    handleAuth(){
    return StreamBuilder(
      stream: FirebaseAuth.instance.onAuthStateChanged,
      builder: (BuildContext, snapshot) {
        if(snapshot.hasData) {
         readData();
          print(flag);
          if(flag ==true)
            return DashboardPage();
          else
            return UserProfile();
        }
        else {
          return SignIn();
        }
      },
    );
  }

  Future<void> readData() async {
    final FirebaseUser user = await _auth.currentUser();
    final userid = user.uid;
    DBRef.child(userid).once().then((DataSnapshot data){
      print(userid);
      if(data.value!=null)
        {
          flag =  true;
          print(data.key);
          print(data.value);
        }
      else{
        print('User not found');
        flag = false;
      }
    });
  }

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

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

  signInWithOTP(smsCode,verId){
    AuthCredential authCreds = PhoneAuthProvider.getCredential(
        verificationId: verId,
        smsCode: smsCode
    );
    signIn(authCreds);
  }
}<
Posted
Updated 22-Jun-20 3:48am

1 solution

Java
Future<void> readData() async {

You have declared readData as an async activity, which means the the caller will not wait for it to finish. Remove the async keyword so that it runs synchronously.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900