0

I've stored user data in shared preferences as users login into the app, the data saved successfully as checked via print in consol, the problem there is as when data is stored in a global variable for later use it gives the null userID.

int? getUserId; // global var 

Future fetch() async {
   var pref = await SharedPreferences.getInstance();
   var userID = pref.getInt('userID');  
    
   //this line prints the correct userID save in pref
   print("userID " + pref.getInt('userID').toString());  
   

   userID = getUserId;
   //this line prints the null userID  
   print("userID -" + userID.toString());  
}

How can we avoid such type of errors as this occurs mostly in case of String type data is printed empty string, anyone explains to me the reason for this problem?

Dominik Šimoník
  • 1,442
  • 10
  • 17

2 Answers2

0

Your problem resides here

userID = getUserId;

You are not assigning any value to the getUserId variable, therefore userID is null

t00n
  • 395
  • 5
  • 12
0

I think you meant getUserId = userID; instead of userID = getUserId;.

That said, global variables are not good programming practice, look at the various state management patterns Flutter provides.

nvoigt
  • 75,013
  • 26
  • 93
  • 142