Shared Preference GetInstance() _TypeError (type '() => Null' is not a subtype of type '(dynamic) => dynamic' of 'f')

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

1 answer

  • answered 2022-01-13 07:27 Pranav

    I think this can be due to null safety.

    Try this-

    SharedPreferences? prefs = await SharedPreferences.getInstance();
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum