Where in the tree to wrap widget with Provider to use the Provider for maintaining state throughout an app?

Issue

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?

Solution

Have you tried wrapping MaterialApp with your Provider()?

Answered By – Sebastian

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *