skip to Main Content
var result;
  
void searching() async{

  var searchData = await FirebaseFirestore.instance.collection('users').where('email',isEqualTo: userEmail).get();
  
    setState(() {
      result = searchData.docs.first;
    });
  }

  
void addFollowing(var username , var email , var phoneNumber) async{
  searching();
  await FirebaseFirestore.instance.collection('users').doc(result).collection('following').doc().set({
    'username':username,
    'email':email,
    'phoneNumber':phoneNumber
  });
  print(result);
}

I have two function searching and addfollowing . The searching function returns a document that matches the given email and sets the id of that document in result . But it returns null for some reason when i call that fucntion in the addfollowing function .

I am using the add following function on an onTap of a gesturedetector. The first press returns null but the second press returns the data .

2

Answers


  1. the searching is not complete then yet. you need to await it. So change

    searching();
    

    to

    await searching();
    

    Also, I believe you need to change this

    void searching() async{
    

    to this as well

    Future searching() async{
    
    Login or Signup to reply.
  2. You should await the searching function in addFollowing to ensure that it completes before you proceed to use the result.

    void searching() async {
      var searchData = await FirebaseFirestore.instance.collection('users').where('email', isEqualTo: userEmail).get();
      setState(() {
        result = searchData.docs.first;
      });
    }
    
    Future<void> addFollowing(var username, var email, var phoneNumber) async {
      await searching(); // Wait for searching() to complete.
      
      if (result != null) {
        await FirebaseFirestore.instance.collection('users').doc(result.id).collection('following').doc().set({
          'username': username,
          'email': email,
          'phoneNumber': phoneNumber
        });
        print(result);
      } else {
        // Handle the case where the user was not found.
        print('User not found.');
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search