Home > Enterprise >  flutter - Wait for the database to respond then navigate
flutter - Wait for the database to respond then navigate

Time:12-16

I'm new to Flutter. Currently I'm trying to create a user record in the database, then switch the window.

await MemberDatabase.insertMember(member);

 Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => ShopKeeperPage(
            email: email,
            loginType: 'normal',
          ),
        ));

Before it adds data to the database, it navigates to the ShopKeeper page instantly which is causing me errors because the data is not inserted in the database yet.

Is there anyway I can make it so that it waits until the data is added in the database and then navigate to the next page?

MemberDatabase class

class MemberDatabase {
  static var memberCollection;
  static connect() async {
    print("trying to connect");
    var db = await Db.create(MONGO_CONN_URL);
    await db.open();
    print("Connected to the database");

    memberCollection = db.collection(MEMBER_COLLECTION);
  }

  static insertMember(Member member) async {
    return await memberCollection.insert(member.toMap());
  }
}

CodePudding user response:

All things equal, from the code you posted, it is waiting for insertMember. Check if insertMember is properly creating the user record as you expect.


However, for a solution. You can rewrite the code to the following. So that you are really sure that navigation is done only after creating the user record fails.

MemberDatabase.insertMember(member).then(() => Navigator.pushReplacement(
    context,
    MaterialPageRoute(
      builder: (context) => ShopKeeperPage(
        email: email,
        loginType: 'normal',
      ),
    ),
  ));

If it doesn't work, then post more code and give more context of what you are doing. Also, check exactly the logic of MemberDatabase.insertMember, that's a place where the issue could be from. Or in the ShopKeeperPage (where Navigation is going to), it could be inappropriately accessing the created member

  • Related