(Flutter) How to use Consumer and ChangeNotifierProvider correctly ? can't find what is missing

815 Views Asked by At

This is the code (Fidev design challenge) step by step copied from source but got an error classes in suspicion are MainPage and LeopardPage have imported all necessary packages Can't figure out what is missing

class LeopardPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    //print(MediaQuery.of(context).size.width);
    return Consumer<PageOffsetNotifier>(

        builder:(context,value,child)
    {
      return Positioned(
        top: 100,
        left: -0.85 * value.offset,
        width: MediaQuery.of(context.watch()).size.width*1.6,
        child: child,
      );
    },child: IgnorePointer(child: Image.asset('assets/leopard.png')),
    );
  }}

2

There are 2 best solutions below

0
On

Main Class is

class _MainPageState extends State<MainPage> {
  final PageController _pageController = PageController();

  @override
  Widget build(BuildContext context) {

    return ChangeNotifierProvider(

      create: (_) {return PageOffsetNotifier(_pageController); },
      child: Scaffold(
        body: Stack(
          children: <Widget>[

            PageView(
              controller: _pageController,
              physics: ClampingScrollPhysics(),
              children: <Widget>[
                //LeopardPage(),
                VultturePage(),
              ],
            ),
            LeopardPage(),
          ],
        ),
      ),
    );
  }
}
0
On

To force the Consumer to use the ChangeNotifier you should provide it before, i.e.

class LeopardPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => PageOffsetNotifier(), // lazy creation of model
      child: Consumer<PageOffsetNotifier>(
        builder:(context, value, child) {
          return Positioned(
            top: 100,
            left: -0.85 * value.offset,
            width: MediaQuery.of(context.watch()).size.width*1.6,
            child: child,
          );
        },
        child: IgnorePointer(
          child: Image.asset('assets/leopard.png')
        ),
      ),
    );
  }
}