I used Navigator.push up to 6 screens to get to the payment page. After Payment, I want to push to the "Payment Successful" page then remove all the previous screens i.e using the back button will return to the very first screen.
NOTE: I have tried pushReplacementNamed and it doesn't work.
I figured it out. It was the Navigator.pushAndRemoveUntil function. Where i had to pass the PaymentSuccessful widget as the newRoute, and the "/Home" route as the predicate
_navPaymentSuccessful(){
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => PaymentSuccessful()
),
ModalRoute.withName("/Home")
);
}
Accepted Answer is correct. But you can try this too.
Navigator.pushAndRemoveUntil<dynamic>(
context,
MaterialPageRoute<dynamic>(
builder: (BuildContext context) => YourPageNameGoesHere(),
),
(route) => false,//if you want to disable back feature set to false
);
even simpler and I think a better way would be to do it this way,
this Schedules a callback for the end of the current persistent frame,to push to route /loginPage and removes all the previous routes,this way you can make sure that all the frames are rendered and then you navigate to next page.
SchedulerBinding.instance.addPostFrameCallback((_) {
Navigator.of(context).pushNamedAndRemoveUntil(
'/loginPage', (Route<dynamic> route) => false);
});
I would Suggest use WillPopScope in your Payment successful page and onWillPop method write following snippet of code:
return WillPopScope(
onWillPop: (){
Navigator.of(context)
.pushNamedAndRemoveUntil('/Home', (Route<dynamic> route) => false);
},
child: Scaffold()
};
Try this if you want pass arguments to new page:
Navigator.of(context).pushNamedAndRemoveUntil(
'/new-route-name',
arguments: {
any object
},
ModalRoute.withName("/the-route-name-that-you-want-back-to-it")
);
Related
I'm not using API or firebase yet, the data is stored locally.
here is my code
======>>
Widget _buildhouse(BuildContext contex, int index){
Size size = MediaQuery.of(context).size;
House house = houselist[index]; //houselist is the list of all houses
return GestureDetector(
onTap: (){
setState(() {]
house = filteredhouse[index]; //this code wont be executed
print(house.price);
});
Navigator.push(context, MaterialPageRoute(builder: (_) => DetailsScreen(house),));
},
so those two lines that I commented on are the important ones I guess, the print code gets executed but not the other one. also if I say "house = filteredhouse[index];" at the beginning, I will get the filtered value. but it won't get changed when clicked the button
solved it by using this function void _filtered(){ setState(() { houselist = filteredhouse; }); } and then calling it inside of setState
Thanks for giving time to read this question and help me.
I have a SideDrawer in my home screen having two options. If I click on 'Tickets' I want Flutter to produce a new page with the tickets.
But, this doesn't seem to be the case. Whenever i tap on 'Tickets', nothing loads. I am pretty sure the function userData() does execute, but doesn't load the new page.
You need to push new screen on the navigation screen. So do this
Future<void> userData(BuildContext context) async {
final FirebaseAuth auth = FirebaseAuth.instance;
final FirebaseUser user = await auth.currentUser();
uid = user.uid;
goToTicketScreen(context,uid); //Add thiis
}
Then define the function as follow
Future<void> goToTicketScreen(BuildContext context,String uid) async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>TicketList(value: uid),
),
);
}
I am using Flutter_bloc package to make a phone auth in flutte, everything work good, but my question is about adding events to the bloc, for example in my application, when i click on button like this code below, the event added to my loginBloc, and everything works good, but when i press back button in android device, and then return back by using normal navigater.pushNamed, and click the button again nothing happen? that mean the event not added to bloc or something like this? can anybody explain this problem? thanks in advance: this is my sample code to add event when click button:
child: RaisedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
loginBloc.add(LoginPressesEvent(
phoNo: _phoneTextController.value.text));
}
},
For adding an 'Event' to 'Bloc' use this code:
BlocProvider.of<'YourBlocClass'>('blocContext').add('YourEvent()'));
'blocContext' is context parameter of `listener in BlocListener' :
BlocProvider(
create: (context) => BlocClass()..add(Fetch()),
child: BlocListener<BlocClass, BaseState>(
listener: (listenerContext, state) {
// listenerContext: store this parameter to Field
// and use that everywhere in your StateClass
},
or context parameter of 'builder in Bloc Builder`
BlocProvider(
create: (context) => BlocClass()..add(Fetch()),
child: BlocBuilder<IndexBloc, BaseState>(
builder: (builderContext, state) {
// builderContext: store this parameter to Field
// and use that everywhere in your StateClass
},
In this app when user click login page is navigate to homepage but when user press back button on home screen then page is navigate to login so this is not a right flow
I triend navigator.pushReplacement but when user press back button while on home screen app is close and go to background and when user open that app from background then instead showing home screen it show login screen so please give suggestions,
Here is my code
LoginScreen
Future<void> login(
String emailId, String password, String accessToken) async {
final dio = Dio(); // Provide a dio instance
String token = AppStrings.keyBearer + accessToken;
var customHeaders = {
AppStrings.authorization: token,
AppStrings.keyContentType: AppStrings.valueContentType
};
dio.options.headers.addAll(customHeaders);
final client = RestClient(dio);
await client
.loginUser(LoginUser(
deviceToken: AppStrings.valueDeviceToken,
lastLoginPlatform: AppStrings.valuePlatform))
.then((res) {
if(res.interests.isEmpty){
AppHelper.showToastMessage(
AppStrings.message_logged_in_successfully);
Navigator.of(context, rootNavigator: true).pop();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => InterestsPage(
userAccesstoken: accessToken,
)));
}
else{
AppHelper.showToastMessage(
AppStrings.message_logged_in_successfully);
Navigator.of(context, rootNavigator: true).pop();
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomePage(
userAccesstoken: accessToken,
userInterests: res.interests
)));
}
}).catchError((Object obj) {
switch (obj.runtimeType) {
case DioError:
final res = (obj as DioError).response;
Navigator.of(context, rootNavigator: true).pop();
logger.e(res.statusMessage);
AppHelper.showToastMessage(AppStrings.message_something_went_wrong);
break;
}
});
}
I used
Navigator.of(context, rootNavigator: true).pop();
for close dialog box
I don't get any error but I want when user press back button on home screen app goes background and when user open that app from background show home screen not login screen
Show me where I made mistake in navigation and how to resolve it.
The method you are looking for is pushReplacement, and the way to go is:
Navigator.of(context).pop();
Navigator
.of(context)
.pushReplacement(
MaterialPageRoute(
builder: (BuildContext context) => InterestsPage(
userAccesstoken: accessToken,
)
)
)
This way, it will pop out of the alert message, and then replace all the previous pages with the one that you want.
However, the logic behing wether the login page needs to be displayed comes down to preference, and since I can't say how to do it without addicional code. I, for example, store the user on a local database after login. This way, even without a connection, there is a way to access the app.
You should use routes on your main file, using PushReplacement just works great there is no problem with it, you should decide where to navigate the user base on if the user logged in before or not, you can use something like share preferences to achieve this functionality. after login just save a pref that says user logged in and then on your splash screen navigate the user to correct screen
This is weird but below code is not working for me. I get a back arrow on the home screen when using below code.
First line below is for dismissing the dialog box. second one is to go to home screen.
Navigator.of(context, rootNavigator: true).pop();
Navigator.of(context).pushReplacementNamed(HomeScreen.id);
This is first time I am facing this kind of situation with pushReplacementNamed. what's going on here ?
It is probably because you have another screen in the stack. When you call pushReplacementNamed, it doesn't replace whole stack with the one you give. Can you try the following code;
// true don't work based on above query condition
Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => true);
// false works
Navigator.of(context).pushNamedAndRemoveUntil(HomeScreen.id, (Route<dynamic> route) => false);
That won't give the required result as you have already even popped the context away before calling another Navigator class. I tried the function Navigator.of(context).pushNamedAndRemoveUntil() but still got my HomeScreen pushed on stack twice with the back button on screen 1. Hence, I finally got this with the inbuilt function Navigator.of(context).popUntil(). You can run this dartpad code https://dartpad.dev/a10ed43452736b5c6b3d1abe6a7eda45 to view the desired effect or view the code below. Below is part of the code from the gist:
...
class ThirdPage extends StatelessWidget{
static const routeName = '/third';
#override
Widget build(BuildContext context){
void _nextPage(){
//Logic here - ***************************
Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst);
}
return Scaffold(
appBar: AppBar(
title: Text('Third Page'),
),
body: Center(
child: Text('Third Page'),
),
floatingActionButton: FloatingActionButton(
onPressed: _nextPage,
child: Icon(Icons.add),
),
);
}
}
Happy coding D:)