Home > Enterprise >  SharedPerference key returning null value in Flutter
SharedPerference key returning null value in Flutter

Time:11-20

I created a user model where I'm saving required data to save in sharedperference so that if user kill the app so I can get it from sharedperference. here is my user model looks like.

class UserModel {
  String? token;
  String? userId;
  String? stripeId;
  String? userName;
  String? userEmailAddress;
 
  UserModel({this.activeCardId,this.token,this.userId,this.stripeId,this.userName});

  UserModel.fromJson(Map<String, dynamic> json) {
    token = json['token'];
    userId = json['user_id'];
    stripeId = json['stripe_id'];
    userName=json['fullname'];
    userEmailAddress=json['email'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data =  <String, dynamic>{};
    data['token'] = token;
    data['user_id'] = userId;
    data['stripe_id'] = stripeId;
    data['fullname']=userName;
    data['email']=userEmailAddress;
    return data;
  }
}

and here is my sharedperference class code, i used provider state management for this


class UserViewModel with ChangeNotifier{

  Future<bool> saveUser(UserModel user)async{

    final SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString('token', user.token.toString());
    sp.setString('user_id',user.userId.toString());
    sp.setString('stripe_id',user.stripeId.toString());
    sp.setString('userName',user.userName.toString());
    sp.setString('userEmailAddress',user.userEmailAddress.toString());
    notifyListeners();
    return true ;
  }

  Future<UserModel> getUser()async{

    final SharedPreferences sp = await SharedPreferences.getInstance();
    final String? token = sp.getString('token');
    final String? userId = sp.getString('user_id');
    final String? stripeId=sp.getString('stripe_id');
    final String? userName=sp.getString('userName');
    final String? userEmailAddress=sp.getString('userEmailAddress');

    return UserModel(
      token: token.toString(),
      userId: userId.toString(),
      stripeId: stripeId.toString(),
      userName:userName.toString(),
      userEmailAddress:userEmailAddress.toString(),
    );
  }

  Future<bool> remove()async{

    final SharedPreferences sp = await SharedPreferences.getInstance();
    sp.remove('token');
    return true;

  }
}

and this is how i'm saving data which I get from Login API response and using this code on Login screen

final userPreference =Provider.of<UserViewModel>(context, listen: false);
userPreference.saveUser(UserModel(userId: value['data']['id'].toString()));

and this is how I'm getting data from sharedPrefernce, using this code of Drawer Widget class

Future<UserModel> getUserDate() => UserViewModel().getUser();
    getUserDate().then((value)async{
      setState(() {
      GlobalVariables.token=value.token.toString();
      });
   });

PROBLEM

The problem is I need to save the stripe_id on sharedpreference so when user get logged in there is screen called Add Card when user click on button an API hits and on its response I'm getting stripe_id and saving it to sharedpereference same as i saved login response, data. But when I came back to Drawer Widget class it prints null value of token. It works fine when I'm not saving stripe_id on sharedpreference.

here is the code how I'm saving stripe_id

final userPreference =Provider.of<UserViewModel>(context,listen: false);
userPreference.saveUser(UserModel(stripe_id: createCard['id'].toString()));

But, when i do above code like this

final userPreference =Provider.of<UserViewModel>(context,listen: false);
userPreference.saveUser(UserModel(stripe_id: createCard['id'].toString()));
userPreference.saveUser(UserModel(token: "22424"));

I get the token value "22424",but I don't want to do it like this. My point is when the sharepreference data is null after saving other data on other key.

Kindly help where I'm doing wrong.

CodePudding user response:

You're simply overriding with NULL values every time you're calling the saveUser() method with an User object with NULL values for it's properties.

You're passing an User object with selected values like stripe_id or token while passing other values NULL and then when you call the saveUser() method, you're saving only the passed values while saving others as NULL by default which get's saved too.

You should check for NULL value before saving each objet's property.


Update your saveUser method with this:

Future<bool> saveUser(UserModel user) async {
  final SharedPreferences sp = await SharedPreferences.getInstance();

  if (user.token != null) sp.setString('token', user.token.toString());
  if (user.userId != null) sp.setString('user_id', user.userId.toString());
  if (user.stripeId != null) sp.setString('stripe_id', user.stripeId.toString());
  if (user.userName != null) sp.setString('userName', user.userName.toString());
  if (user.userEmailAddress != null) sp.setString('userEmailAddress', user.userEmailAddress.toString());

  notifyListeners();
  return true;
}
  • Related