使用flutter中的共享首选项将数据保存为对象



因为我正在用Flutter改善我的自我,我有一个用户模型,它有宠物狗宠物模型。每个模型都有一个条目的id。我需要知道如何使用Flutter中的共享首选项将这些数据保存为具有ID值的对象。我从互联网上学习了一些例子,但还没有想出解决方案。下面是我迄今为止试过的一个。

用户模型

int id;
String userName;
String userEmail;
String userPassword;
String userAddress;
String userPhoneNo;
String userCountry;
bool isSubscribed = false;
String role;

User({this.userName, this.userEmail, this.userPassword, this.userAddress,
this.userPhoneNo, this.userCountry, this.isSubscribed, this.role});
factory User.fromJson(Map<String, dynamic> parsedJson) {
return new User(
userName: parsedJson['userName'] ?? "",
userEmail: parsedJson['userEmail'] ?? "",
userPassword: parsedJson['userPassword'] ?? "",
userAddress: parsedJson['userAddress'] ?? "",
userPhoneNo: parsedJson['userPhoneNo'] ?? "",
userCountry: parsedJson['userCountry'] ?? "",
isSubscribed: parsedJson['isSubscribed'] ?? false,
role: parsedJson['role'] ?? "",
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userName'] = this.userName;
data['userEmail'] = this.userEmail;
data['userAddress'] = this.userAddress;
data['userPhoneNo'] = this.userPhoneNo;
data['userCountry'] = this.userCountry;
data['isSubscribed'] = this.isSubscribed;
return data;
}
}

宠物模型

in id;
String petImage;
String petName;
int petAge;
String petBreed;
double petWeight;
double petIdealWeight;
String petSex;
String petEatBones;
String petBirthDate;
Pet(this.petImage, this.petName, this.petAge, this.petBreed, this.petWeight,
this.petIdealWeight, this.petSex, this.petEatBones, this.petBirthDate);
}

我需要使用共享偏好保存和查看数据的地方

var userData = {
'username': _userName,
'email': _userEmail,
'password': _userPassword,
'address': _userAddress,
'country': _selectedCountry.toString(),
'mobile': mobile,
'subscribed': _isSubscribed,
'role': _role,
};
//save user data in userPrefs
userPrefs = await SharedPreferences.getInstance();
// var userJson = userPrefs.getString('user');
Map decode_options = jsonDecode(jsonString);
String user = jsonEncode(User.fromJson(decode_options));
userPrefs.setString('userData', user);
//get those data
@override
void initState() {
_getUserInfo();
super.initState();
}
void _getUserInfo() async {
userViewPrefs = await SharedPreferences.getInstance();
// get  user info from prefs //
Map jsonString = jsonDecode(userViewPrefs.getString('userData'));
var user = User.fromJson(jsonString);
setState(() {
userData = user;//userStringDecode;
});

你可以试试这个。

设置数据

userPrefs = await SharedPreferences.getInstance();
String user = jsonEncode(User.toJson(your json));  //json data
userPrefs.setString('userData', user);

获取数据

userViewPrefs = await SharedPreferences.getInstance();
String user= userViewPrefs.getString('userData')
Map jsonString = json.decode(user);
User user = User.fromJson(jsonString);

相关内容

  • 没有找到相关文章

最新更新