flutter - Wait for the database to respond then navigate - flutter

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

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

Rebuild app or delete cache when redirect to home page Flutter

I have an app where when I logout with Firebase Auth, user's datas are still there, and I need to Hot restart the app to totally remove them.
I didn’t find a way to improve the signout method, so I want to try to rebuild app when user logout, or maybe delete the cache so user’s datas will no longer exist in app.
I have done some research but I can’t find any solution that can help me.
EDIT : Here's how I logout
Future<void> signOut() async {
await FirebaseAuth.instance
.signOut()
.then((value) => print('Sign Out'))
.onError((error, stackTrace) => print('Error in signed out'));
}
IconButton(
onPressed: () async {
await signOut();
Navigator.of(context, rootNavigator: true)
.pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return const OnBoardingPage();
},
),
(_) => false,
);
},
icon: const Icon(Icons.logout))
I know that user's data are still there because I can display user.email in my onBoardingPage (where technically no data can be there because I logout previously).
Here a preview of my onBoardingPage :
After that, if I want to connect with another account, I will be connected to the previous user's session. The same if I want to create a new account, all new user's data will be into the previous connected user. To fix this problem, in development mode, I need to hot restart the app.
It seems like the user is not totally logout.

How to get returned value from Navigator.pop using Navigator.restorable?

Currently my original way of getting values between screen using Navigator.pop was like this:
Second screen goes back to home screen and passes a boolean:
Navigator.pop(context, false);
Home screen awaiting for the Navigator and capturing the value:
var bookmarked = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const CorePage()),
);
However I've recently started using restorable to restore states when the app randomly closes such as:
static Route<void> _staticGoToCoreWorkout(context, arguments) =>
MaterialPageRoute(builder: (context) => const CorePage());
Navigator.restorablePush(context, _staticGoToCoreWorkout);
The problem I'm having is that something like this doesn't work anymore:
var bookmarked = Navigator.restorablePush(context, _staticGoToCoreWorkout);
How can I go about getting the boolean value (or any value really) that's passed from the Navigator.pop back to the previous screen when I'm using restorable?
UPDATED:
Adding await doesn't yield results either. It will always run pass the code.
var bookmarked = await Navigator.restorablePush(context, _staticGoToCoreWorkout);

Wait for Navigator.pop animation

Currently, I have a seperate page to view a specific entity.
On the seperate page, users may delete this entity.
To make the code more "clean", I want to first pop this separate page and then delete the entity from the list. However, I cannot delete it right away because there is a short time frame where the page still exists. My workaround is to add a delay to make sure that the page is "disposed". Is there a cleaner way?
onTap: () async {
final result = await Navigator.push<MyPageResult>(context, MaterialPageRoute(
builder: (_) => MyEntityPage(id: id),
);
if (result == MyPageResult.delete) {
// wait for page to be correctly disposed (animation to be finished)
// this is the dirty approach, is there a cleaner way?
await sleepAsync(1000);
ref.read(dataProvider.notifier).deleteEntity(id: id);
}
}

How to move fast after fetching data from api on pressing button Flutter

I want to ask if there is a future function who gives data from api and i want to get that data when i pressed the button and i want some particular data like id of user i am using function like
onPressed: () async {
var data = await getLogin()
if(data.id == 0){
Navigator.push(context,
MaterialPageRoute(builder: ((context) => Login())));
else {
Navigator.push(context,
MaterialPageRoute(builder: ((context) => Order())));
}
}
Can you tell me why it is taking time when i am pressing button to open new screen and can any one tell me the solution
it is taking time because it await for data. It is a async function and this await keyword wait until you didn't get the data back..
Problem is that if you not use await keyword then data.id throw a null safety error....
So solution is Future Provider... Call the api using the any state management solution like provider and navigate without checking the condition... Then update Ui after getting data from Provider..

Flutter-Backendless User Login __ How to Validate User Credentials (Email and Password) to move from Login Page to Home Page

Newbie mobile developer here. I'm trying to implement User Logins with Backendless but I don't know whats the best way to do it, especially to avoid making too many API calls.
I know there are several malpractices (especially UX) here but I'm really just trying to get the logic right first.
In the following excerpt, I try making a log-in and when it's done give the user access to the app. If its not successful Id like the alert to be made. However, the app shows the alert independently of the credentials being correct. It's like the if starts executing before the login has been completed.
I'm not looking for a workaround, I'm a noob developer and honestly, don't know the best way to handle this. I would be very appreciative of help. Thanks, guys!
Backendless.userService.login(email, password).then((user) => boologin=true);
if (boologin==true) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Home(),
),
);
} else {
showBasicAlert(context,
"Wrong username or password", "");
boologin is always false when it reaches to if. Because login is asynchronous and before boologin = true being set, code flow continues. Try to change it like here
await Backendless.userService.login(email, password);
Then to set boologin = true
As Marat said, most of the calls to the Flutter Backendless SDK is asynchronous and
you can use the await keyword to wait for a Future to complete. Or you can perform actions in the response's body.
Here is the most convenient way to handle Backendless SDK calls:
void logIn(email, password) {
Backendless.userService.login(email, password)
.then((loggedInUser) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Home(),
),
);
})
.catchError((onError) {
showBasicAlert(context, "Wrong username or password", "");
});
}