Search code examples
fluttersharedpreferences

Save in shared preference while exit page flutter


I am trying to save INT value in shared preference while exit page. So I used dispose method to save but It gives error.

Tried to listen to a value exposed with provider, from outside of the widget tree.

 This is likely caused by an event handler (like a button's onPressed) that called
 Provider.of without passing `listen: false`.

    To fix, write:
    Provider.of<AuthProvider>(context, listen: false);

   It is unsupported because may pointlessly rebuild the widget associated to the
      event handler, when the widget tree doesn't care about the value.

   The context used was: PlayPage(dependencies: [_InheritedProviderScope<AuthProvider>, MediaQuery], 
   state: _PlayPageState#d7691(lifecycle state: defunct))
    'package:provider/src/provider.dart':
       Failed assertion: line 242 pos 7: 'context.owner.debugBuilding ||
      listen == false ||
      debugIsInInheritedProviderUpdate'

Code :

 @override
void dispose() {


Provider.of<AuthProvider>(context).storeVideoTiming( _duration?.inSeconds ?? 0);
 super.dispose();

 }

Provider page :

 storeVideoTiming(int timins) async{

   SharedPreferences prefs = await SharedPreferences.getInstance();

   prefs.setInt('VideoCount', timins);
    }

Solution

  • Just change this line :

    Provider.of<AuthProvider>(context).storeVideoTiming( _duration?.inSeconds ?? 0);
    

    with :

    Provider.of<AuthProvider>(context, listen: false).storeVideoTiming( _duration?.inSeconds ?? 0);