pop a specific route with result in auto route flutter - flutter

I'm using auto_route as my app's navigation system. I need to do something like the finish() function in android activity which closes the current activity that it's being called from. How can I achieve this in flutter?

As shown here:
In your router config specify which data type is returned.
e.g.: (here a Set is returned)
AutoRoute<Set<User>>(
page: UserSelectPage,
),
In your Page, you have to pop the values:
onPressed: () async {
await AutoRouter.of(context).pop(yourValues);
},
Then in your code you can call this to push the page and work with the return value.
onPressed: () async {
final Set<User>? users = await AutoRouter.of(context)
.push<Set<User>>(UserSelectPageRoute());
if (users != null) {
await doOtherStuffWithYourNewData(users);
}
}

Related

How to call a function when returning to view/controller with `Get.back()`?

I am switching from the home view to another using Get.toNamed(Routes.DETAIL). When I want to return from the details view to the home view, I am calling Get.back() (or the user is using the back button of the devices).
Back on the home view, I would like to fetch all data from my database again.
Is there any function that is triggered when I am leaving a few and returning to it, so I can put my logic there?
Thank you
I would suggest you to use Get.offNamed() instead of Get.toNamed() as the offNamed() function will clear the data stored in catch and thus will again call the API declared in onInit() or onReady() lifecycle when returning back to that screen.
In Getx they have a funtion like
Get.back(result:"result");
so in order to trigger some funtion when going back to any page route
try doing this as the document written
final gotoHome = await Get.toNamed(Route.name); // or use the simple one Get.to(()=> Home());
then if you trigger to go back in page you should indicate some result e.g.
from back button in phone using willpopscope or a back button in UI.
Get.back(result:"triggerIt"); // this result will pass to the home.
so in will use
// It depend on you on where you gonna put this
// onInit or onReady or anything that would trigger
someTrigger() async{
final gotoHome = await Get.toNamed(Route.name);
if(gotoHome == "triggerIt"){
anyFuntionYouwantoTrigger();
}
}
for more info about it try to read the documentation.
https://github.com/jonataslaw/getx/blob/master/documentation/en_US/route_management.md
Edited: // Maybe some answer will pop up for better
I do have one but it's not that quite a real practice just a sample
e.g // sample you are now in the current page and this page is also connected to homecontroller or using Get.find() it need to bind the controller to the page;
class BindingHome with Bindings{
#override
void dependencies() {
Get.lazyPut(() => HomeController(), fenix: true);
}
}
then from GetPage add Binding
GetPage(
name: "/currentpage",
binding: BindingHome(),
page:() => HomeView(),
),
so while homecontroller is bind to the current page you are now so
// lets assume this one is put to the CurrentController
final homeController = Get.find<HomeController>();
so while calling back button on ui or willpopscope
when back try to trigger the function from home
gotBackfunction(){
Get.back();
homeController.anyFuntionYouwantoTrigger();
}
No you can't really call a function when doing so.
You should be using callback function just before popping the view.
onBackClick() async {
Get.lazyPut<MainController>(
() => MainController(),
);
controller.allItems.refresh();
Get.back();
}
Here is an example how you can do it without any complications:
WillPopScope(
onWillPop: () async {
await onBackClick();
return Future(() => false);
},
child: Scaffold(
appBar: CustomAppBarWithBack(
title: "Appbar",
OnClickBack: onBackClick,
),
body: Widget(),
),
);

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..

1 QuerySnapshot returning null in Flutter web app but gives result in the Android console

I am having an issue where the QuerySnashot from the firestore giving correct value when printing in the android console but returns a null when building it on the flutter web app. Can someone please assist on what I am doing wrong?
Here is the function giving me the correct print:
countpassengers() async {
String collection = "users";
QuerySnapshot _myDoc = await firebaseFiretore.collection(collection).get();
List<DocumentSnapshot> _myDocCount = _myDoc.docs;
print("Number of Users: :::::::::::::");
print(_myDocCount.length); // Count of Documen
totalusers = _myDocCount.length.toString() ;//ts in Collection
print (totalusers.toString());
return totalusers ;
}
and here is how I am calling it (returning null) somehow
InfoCard(
title: "Number of Passengers",
value: totalusers.toString(),//"3",
onTap: () {},
topColor: Colors.orange,
),
When you are returning the output from a function to State you need to rebuild the state by calling setState function.
By calling setState, the whole StatefulWidget knows something is updated and rebuild the state with new data. So insert setState after calling your Firestore function in the class. It could be inside a function or inside onTap: (){}.
If you call that function inside your onTap: (){}, don't forget to add async like that: onTap: () async{} and await your returning data.

Flutter: Send data back to specific list item

I am trying to send data to a specific list item on the screen.
The logic is that you click on the specific card in the list it opens a second screen with an input field (see images below). You then submit your input and it changes the value of that specific card on the first screen.
What is the best way to achieve this?
You can do it like this:
Instead of only pushing to another page, await for a return
final data = await Navigator.push(context,
MaterialPageRoute(builder: (context) => InputScreen()));
setState(()
myList.add(data); //do whatever you want with the return here
});
And in your InputScreen you do this:
Navigator.of(context).pop(data);
Also, if your user press the back button of their phone, it will return null, so you will need to handle that.
You can achieve this by doing the steps below:
1) In the onTap function of the card, await the result by adding the code below:
// on tap function of your card
onTap: () async {
// navigate to the second screen and wait for input user enters
final result = await Navigator.push(context
MaterialPageRoute(builder: (context) => SecondScreen()));
// call setstate to see your changes
setState(() {
// add the input to your list
myList.add(result);
);
},
1) In the onTap function of your submit button send back the result by adding the code below:
// ontap function of your submit button
onTap: () {
// value is what the user has inputted in the text field
Navigator.pop(context, value);
},

Firebase Cloud Messaging onLaunch callback

My app structure is a little bit mess, but I have to add this patch first and then I'll restructure the entire logic. The thing is I first check if there's a firebase user, then if there is one I use StreamBuilder to get the current user profile from Firestore, then I have the _firebaseMessaging.configure method because onLaunch and onResume I use this callback:
void _navigateToGestorResevas(Map<String, dynamic> message, User currentUser) {
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
GestorScreen(user: currentUser)));
}
Because I need to send the User to this screen where he fetch the message from firebase.
onResume this works fine, but onLaunch it goes to the screen and fetch the data but there are like 20 seconds where there are some kind of glitch. It switch like 20-30 times between two states where I have and no have snapshot data in this _initState func:
final snapshot = await _dbRef.child('mensajes').child(widget.user.id).once();
if (snapshot.value != null) {
setState(() {
hayMensajes = true;
});
final data = snapshot.value;
for (var entry in data.entries) {
Message message = Message.fromJson(entry.value);
setState(() {
message.add(message);
});
}
} else {
setState(() {
hayMensajes = false;
});
}
Anyone have an idea what am I doing wrong?
If I am not mistaken, there are some active issues about FCM onLaunch callback with flutter. Some of them are still not fixed. One of the problems most people had to face was that onLaunch callback being called multiple times. I don't know why it happened, but as in your case, you can possibly get rid of the issue by some temporary fixes.
If the same screen is getting pushed over and over again, and glitching, you can pop the stack until it reaches the one you meant to open and set a condition to push navigator only if the new route is different from the old one. Using the named routes,
Navigator.popUntil(context, ModalRoute.withName(routeName));
if (ModalRoute.of(context).settings.name != routeName) {
Navigator.pushNamed(context, routeName);
}
I am not sure if that was the problem you asked, but I hope at least my answer helps somehow.