问题
I am learning about provider + ChangeNotifier for state management, but I can't find any official guidance on how to implement a Navigation from a ChangeNotifier
.
Let's say we improve the provider_shopper
sample here, so when the user clicks BUY, the CartModel
does some buying logic and then Navigates to a Order Review page. How's this navigation should be implemented?
Do we provide a callback for the CartModel
, so it will call it and trigger a Navigation on the UI?
回答1:
There might be a simpler and more elegant solution but I could only think of using one page and doing away with the Navigator:
@override
Widget build(BuildContext context) {
final appProvider = Provider.of<AppProvider>(context);
switch (appProvider.getCurrentPage()) {
case 'home': return homePage(appProvider);break;
case 'test': return testPage(appProvider,context);break;
}
return homePage(appProvider);
}
Each "page" is just a function that returns a Wigdet(a Scaffold):
Widget testPage(AppProvider appProvider,BuildContext context) {
return WillPopScope(
onWillPop: () {return controlBackButton(appProvider,context);},
child: Scaffold(
appBar: AppBar(
title: Text('Test Page'),
),
Changing the page:
void changePage(AppProvider appProvider,String page) {
setState(() {
appProvider.setCurrentPage(page);
});
}
All pages except for the home page need to be wrapped in a WillPopScope widget in order to make the back button navigate to the home screen:
Future<bool> controlBackButton(AppProvider appProvider) async{
setState(() {
appProvider.setCurrentPage('home');
});
return false;
}
It's not the best solution but a good start, I think.
来源:https://stackoverflow.com/questions/57330108/how-to-navigate-from-changenotifier