1

My app has a simple home page screen

class StartPage extends StatelessWidget {}

and two additional screens. Users are routed to the additional screens with code like

Navigator.push(
       context,
       MaterialPageRoute(
         builder: (BuildContext context) => Page2(),
       ),

and

Navigator.push(
       context,
       MaterialPageRoute(
          builder: (BuildContext context) => Page3(),
       ),

Page2() has a simple stopwatch which I implement with a Provider. I want to add the identical stopwatch code to Page3(). I would think StartPage() is further up the "tree" than Page2() and Page3(), and that if I wrap StartPage's build method with a Provider (along with Consumer widget code inside the relevant classes)

 @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<StopWatchProvider>(
      create: (context) => StopWatchProvider(),
      child: Scaffold()

then the stopwatch should work as expected in both Page2() and Page3() (supported by this SO post). But this throws an error about being unable to find a Provider and, instead, I need to wrap builders for Page2() and Page3() with a Provider.

What am I missing?

Al C
  • 5,175
  • 6
  • 44
  • 74

1 Answers1

1

Have you tried wrapping MaterialApp with your Provider()?

Sebastian
  • 3,666
  • 2
  • 19
  • 32
  • I know this is going to make me sound stupid, but I've tried wrapping so many things now that I've forgotten. Should I wrap `MaterialApp`? (Just this minute I saw https://stackoverflow.com/questions/60045822/navigator-push-error-could-not-find-the-correct-provider-above-this-consumer?rq=1) – Al C Feb 25 '20 at 17:11
  • Yes, that asures you that you can access that provider everywhere in your app. If that's what you need, go for it – Sebastian Feb 25 '20 at 17:12
  • 1
    Yup, that did it :-) ... I'm still unsure why my original code didn't work, but you definitely solved the issue. – Al C Feb 25 '20 at 17:20