Flutter - Execute code before setting Home Page

203 views Asked by At

I have this set up:

  @override
  void onReady() {
    super.onReady();
    firebaseUser = Rx<User?>(auth.currentUser);
    firebaseUser.bindStream(auth.userChanges());
    ever(firebaseUser, _setInitialScreen);
  }

  _setInitialScreen(User? user) async {
    if (user == null) {
      Get.offAll(() => AuthenticationScreen());
    } else {
      if (UserModel.ROLE == "fieldOwner") {
        Get.offAll(() => FieldOwnerHome(user: user));
      } else {
        Get.offAll(() => HomeScreen(user: user));
      }
    }
  }

The _setInitialScreen function gets called as soon as a user signs up

I want this code to be executed before that so that the correct Home Screen can be displayed

   void signUp() async {
    showLoading();
    try {
      await auth
          .createUserWithEmailAndPassword(
              email: email.text.trim(), password: password.text.trim())
          .then((result) {
        String? _userId = result.user?.uid;

    ///THESE 2 SHOULD FINISH EXECUTION FIRST
        _addUserToFirestore(_userId);
        _initializeUserModel(_userId);

        _clearControllers();
      });
    } catch (e) {
      debugPrint(e.toString());
      Get.snackbar("Sign Up Failed", e.toString());
    }
  }


   _addUserToFirestore(String? userId) {
    var role = (authController.isFieldOwnerChecked.value)
        ? "fieldOwner"
        : "user";

    usersCollection.doc(userId).set(
      {
        "name": name.text.trim(),
        "id": userId,
        "email": email.text.trim(),
        "role": role,
      },
    );


  _initializeUserModel(String? userId) async {
    userModel.value = await usersCollection
        .doc(userId)
        .get()
        .then((doc) => UserModel.fromSnapshot(doc));
  }

What is happening is the Get.offAll() in the _setInitialScreen gets called first; thus the wrong Home Screen gets called.

0

There are 0 answers