0

Flutter Version :

I am getting an exception in line SharedPreferences prefs = await SharedPreferences.getInstance();.

Exception has occurred.
_TypeError (type '() => Null' is not a subtype of type '(dynamic) => dynamic' of 'f')

The same code is working properly in sign-in function.

Code:

appBar: AppBar(
        title: const Text('Messanger Clone'),
        actions: <Widget>[
          InkWell(
            onTap: () {
              AuthMethods().signOut().then(() {
                Navigator.pushReplacement(
                    context, MaterialPageRoute(builder: (context) => SignIn()));
              });
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: const Icon(Icons.exit_to_app),
            ),
        ),
    ],
),

class SharedPreferenceHelper{
    Future<bool> saveUserId(String userId) async {
        SharedPreferences prefs = await SharedPreferences.getInstance(); //Working
        return prefs.setString(userIdKey, userId);
    }
}

class AuthMethods {
//Other Methods
signOut() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance(); // Not working
      prefs.clear();
      await auth.signOut();
    } on Exception catch (error) {
      if (kDebugMode) {
        print('Exception : $error');
      }
    }
  }
}

Flutter 2.8.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 77d935af4d (4 weeks ago) • 2021-12-16 08:37:33 -0800
Engine • revision 890a5fca2e
Tools • Dart 2.15.1

Dark Sorrow
  • 1,681
  • 14
  • 37
  • Try await prefs.clear(); Also, make sure that that string gets added to the sharedpreference in the function. – Pranav Jan 13 '22 at 06:01
  • @Pranav Tried but no joy. Code is failing on line `SharedPreferences prefs = await SharedPreferences.getInstance();` before it executes `prefs.clear();` and gives the same exception. – Dark Sorrow Jan 13 '22 at 07:11

2 Answers2

0

I think this can be due to null safety.

Try this-

SharedPreferences? prefs = await SharedPreferences.getInstance();
Pranav
  • 326
  • 1
  • 10
0

The above will occur when you setup the plugin for the first time, so it has to be reinstalled.

Therefore, uninstall and reinstall your application

H_R_S
  • 21
  • 1
  • 3