Assume that I'm on page-A now. I navigate to page-B. When I pop the page-B and come back to page-A, currently nothing happens. How can I reload page-A and load the new API data from the init state of page-A? Any Ideas?
CodePudding user response:
first main page
void refreshData() {
id ;
}
FutureOr onGoBack(dynamic value) {
refreshData();
setState(() {});
}
void navigateSecondPage() {
Route route = MaterialPageRoute(builder: (context) => SecondPage());
Navigator.push(context, route).then(onGoBack);
}
second page
RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go Back'),
),
more details check here
CodePudding user response:
From the explanation that you have described, so when you are popping the page. This below Code will be on the second page.
Navigator.of(context).pop(true);
so the true parameter can be any thing which ever data that you want to send.
And then when you are pushing from one page to another this will be the code.
this is on the first page.
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const PageOne()),
);
so if you print the result you will get the bool value that you send from the second page. And based on bool you can hit the api. if the bool true make an api call.
Let me know if this works.
CodePudding user response:
There are one more solutions for this situtation.
İf you want to trigger initState again
- You can use pushAndRemoveUntil method for navigation. ( if you use only push method this is not remove previous page on the stack)
- You can use key
- You can set any state manegement pattern.( not for only trigger initState again)
CodePudding user response:
There are 2 ways:
Using
await
await Navigator.push(context, MaterialPageRoute(builder: (context){ return PageB(); })); /// /// REFRESH DATA (or) MAKE API CALL HERE
Passing
fetchData
constructor to pageB and call it on dispose of pageBclass PageA { void _fetchData() {} Future<void> goToPageB(BuildContext context) async { await Navigator.push(context, MaterialPageRoute(builder: (context) { return PageB(onFetchData: _fetchData); })); } } class PageB extends StatefulWidget { const PageB({Key? key, this.onFetchData}) : super(key: key); final VoidCallback? onFetchData; @override State<PageB> createState() => _PageBState(); } class _PageBState extends State<PageB> { @override void dispose() { widget.onFetchData?.call(); super.dispose(); } @override Widget build(BuildContext context) { return Container(); } }