flutternullsharedpreferencesalternate

What is the alternate of shared preference in flutter


I am developed an app, which is almost complete it is in deployment stage. But, now i am in huge problem, i uninstall the app from emulator and then run it again and it sends me the error of shared preference version, that flutter updates it version from 2.0.5 to 2.0.7 so i change the version of shared preference from 2.0.5 to 2.0.7, then when i run the app it builds successfully but i can't move to next screen. my api is running it is sending me 200 response status code.

i am using shared preference in login screen, so that when user logged in i am getting its all details in response.data and then passing the data from login screen to home and other screen using shared preference.

here is the login function code


var data={};
  Future login() async {
    Dio dio = new Dio();
    
    try {  
      data = {
        'username':"abc",
        'password':"abc123",
        'date': "2021-08-29"
      }; 
     await dio
          .post(localhostUrlLogin, data: json.encode(data),)
          .then((onResponse) async {
          print(onResponse.statusCode);

        String name = (onResponse.data['User']['username']);    
        String email = (onResponse.data['User']['email']);

      //here i am using shared preference to pass the name and email to home and other screen
        myPrefs.setString('name', name);
        myPrefs.setString('email', email);

//here i am calling the home screen
        Navigator.push(
              context, new MaterialPageRoute(builder: (context) => Home()));
      
      });
    } catch (e) {
         showDialog(
            context: context,
            builder: (BuildContext context) {
              return AdvanceCustomAlert(
                title: "Connection Error",
                descriptions: "Connection error",
                icon: Icons.error,
                bgcolor: Colors.red,
                fgcolor: Colors.red,
              );
            });
        
      } 
  }

When i click on login button it send this output in terminal


I/flutter (11877): 200
I/flutter (11877): NoSuchMethodError: The method 'setString' was called on null.
I/flutter (11877): Receiver: null
I/flutter (11877): Tried calling: setString("name", "abc")

how to fix this issue?


Solution

  • If myPrefs is a variable for SharedPreference instance then you should know that we must await an Instance of it before we can do anything with it. According to the message in the console myPrefs seems to be null

    Try:

    var myPrefs = await SharedPreferences.getInstance();
    
    await myPrefs.setString('name', name);
    await myPrefs.setString('email', email);