1

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?

Michel Feinstein
  • 13,416
  • 16
  • 91
  • 173

1 Answers1

-2

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.

Willie Nandi
  • 621
  • 6
  • 9
  • I am pretty sure this solution isn't a good one, first you will lose the platform independent navigation animation, second you made all that code for a simple navigation that should be just one line of code, using what the framework already has, my suggestion of using a callback is way simpler. – Michel Feinstein Aug 02 '19 at 20:14
  • It would be great if you can post an answer with code snippets. The challenge I had was that if you wrap the MaterialApp with a ChangeNotifierProvider, the provider will not have a Navigation object. – Willie Nandi Aug 03 '19 at 09:44
  • The Consumer will have a context. I can give an answer, but I was hoping to get one from the community. – Michel Feinstein Aug 03 '19 at 21:13