how to use consumer correctly in flutter provider package

2.4k Views Asked by At

This is the error message

: The following NoSuchMethodError was thrown building Consumer<PageOffsetNotifier>(dirty,
: dependencies: [_InheritedProviderScope<PageOffsetNotifier>]):
: The method 'unary-' was called on null.
: Receiver: null
: Tried calling: unary-()

this is the class with consumer

class LeopardImage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<PageOffsetNotifier>(
      builder: (context,notifier,child) => Positioned(
          width:300, left: -notifier.offset,
          child: child,
      ),
      child: Image.asset('assets/leopard.png'),
    );
  }
}

here PageOffsetNotifier is the class which extends with ChangeNotifier and passed on to ChangeNotifierProvider

the notifier will detect the change in offset value while swiping one page to another and perform the desired function.....

Please tell me what I'm missing or done wrong in the consumer, as a result, I'm getting this error

2

There are 2 best solutions below

0
On

To Pass the context from a page to another using provider. Then it's always wise to use its object

ChangeNotifierProvider.value(
    value: object from Provider,
    child: the page you want to move
)
0
On

The parent widget of this will be :

ChangeNotiferProvider<ClassName>(
    
   oncreate: (context)=>ClassName(),
),

With this you can use consumer inside.