I have some values that are stored in shared prefrences and in my case when I need to use these values in different screens, I am calling them in each one of them in a method like this:
Future <String> getUserInfo() async{
SharedPreferences preferences = await SharedPreferences.getInstance();
String username = preferences.getString('$userID,name')?? "No name found";
String weight = preferences.getString('$userID,weight') ?? "no wight found";
String height = preferences.getString('$userID,height') ?? "no Height found";
String gendertype = preferences.getString('$userID,genderType') ?? "no gender Type found";
String birthdate = preferences.getString('$userID,dateOfBirth') ?? "no date found";
userName = username;
userWeight = weight;
userHeight = height;
userGender = gendertype;
birthDateInString = birthdate;
return username;
}
That is working fina and all and I am getting the values everytime but then this doesnt feels right. I think I should only call them once and then pass them globally between screens or somehow keep them always stored for later use.
How can I achieve that?
CodePudding user response:
using provider packages
https://pub.dev/packages/provider
You can store the value and call it when you need it.
class UserInfo extends ChangeNotifier{
///Implement your Data Model And Method
}
call
//If you need to update the UI
context.watch<UserInfo>().yourValueName or Method
//If you need to not update the UI
context.read<UserInfo>().yourValueName or Method