我有一些存储在共享首选项中的值,在我的情况下,当我需要在不同的屏幕中使用这些值时,我会用这样的方法在每个屏幕中调用它们:
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;
}
这很有效,我每次都得到了价值,但这感觉不对。我认为我应该只调用它们一次,然后在屏幕之间全局传递它们,或者以某种方式始终保存它们以备将来使用。
我怎样才能做到这一点?
使用provider packages
https://pub.dev/packages/provider
您可以存储该值,并在需要时调用它。
class UserInfo extends ChangeNotifier{
///Implement your Data Model And Method
}
调用
//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