我有一个问题。应用启动后,我需要在应用启动时保存和检索json对象。因此,我提出了一个简单的get
请求,该请求从我的响应中返回了用户详细信息,并保存为具有共享首选项的对象。因此,保存后,我会立即反序列化,以便我可以随时使用。问题在于它在首次启动时不起作用。只能在第二次启动后检索保存的对象。我已经尝试了很多故障排除方法,但都没有成功。
UserClass
class User {
final String first_name;
final String email;
final String last_name;
final String country;
final String gender;
final String phone;
final String profile_image;
final String created_at;
final String updated_at;
final String category;
final String industry;
final String bio_interest;
final String fav_quote;
final String current_job;
final String state_of_origin;
int id = 0;
User(this.first_name, this.email, this.last_name, this.country, this.gender, this.phone,
this.profile_image, this.created_at, this.updated_at, this.category, this.industry, this.bio_interest,
this.fav_quote, this.current_job, this.state_of_origin, this.id);
Map<String, dynamic> toJson() => {
'first_name': first_name,
'email': email,
'last_name': last_name,
'country': country,
'gender': gender,
'phone': phone,
'profile_image': profile_image,
'created_at': created_at,
'updated_at': updated_at,
'category': category,
'industry': industry,
'bio_interest': bio_interest,
'fav_quote': fav_quote,
'current_job': current_job,
'state_of_origin': state_of_origin,
'id': id,
};
User.fromJson(Map<String, dynamic> json):
first_name = json['first_name'],
email = json['email'],
last_name = json['last_name'],
country = json['country'],
gender = json['gender'],
phone = json['phone'],
profile_image = json['profile_image'],
created_at = json['created_at'],
updated_at = json['updated_at'],
category = json['category'],
industry = json['industry'],
bio_interest = json['bio_interest'],
fav_quote = json['fav_quote'],
current_job = json['current_job'],
state_of_origin = json['state_of_origin'],
id = json['id'];
}
NetworkClass
class Network(){
static Future fetch(var authToken, var endPoint) async {
var uri = host + endPoint;
try {
final response = await http.get(
uri,
headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': authToken, },
);
final responseJson = json.decode(response.body);
SharedPref sharedPref = SharedPref();
sharedPref.save("user", responseJson);
return responseJson;
} catch (exception) {
print(exception);
if (exception.toString().contains('SocketException')) {
return 'NetworkError';
} else {
return null;
}
}
}
}
主屏幕
String _firstName = "";
String _lastName = "";
String _nationality = "";
String _fav_quote = "";
String _industry = "";
String names = "";
String _profile_image = "";
String _appBarText = "Welcome";
@override
void initState() {
super.initState();
checkLoginState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
}
Future checkLoginState() async {
sharedPreferences = await SharedPreferences.getInstance();
if (sharedPreferences.getString("token") == null) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (BuildContext context) => LoginScreen()),
(Route<dynamic> route) => false);
} else {
Network.fetch("Bearer " + sharedPreferences.getString("token"),
AuthUtils.endPointProfile);
//read value from shared preference
User user = User.fromJson(await sharedPref.read("user"));
//that line only works from second launch
setState(() {
//these variables dont get set on first launch
_appBarText = "Welcome, " + user.first_name;
id = user.id;
_firstName = user.first_name;
_lastName = user.last_name;
_nationality = user.country;
_fav_quote = user.fav_quote;
_industry = user.industry;
_profile_image = user.profile_image;
names = _firstName + " " + _lastName;
});
try {
} catch (Excepetion) {
// do something
}
}
}
}
答案 0 :(得分:0)
我不确定您如何在SharedPref
类中存储数据,但是要实现您提到的功能,可以按照以下步骤操作:
从服务器获取数据后,您可以将数据作为字符串存储到SharedPreferences
中,如下所示
final SharedPreferences _prefs = await SharedPreferences.getInstance();
await _prefs.setString("users", response.body);
// your response.body should be a `String`,
// if it is not `String` or it is a JSON you can convert it by
// json.encode(response.body);
如果需要,您可以从SharedPreferences
的任何地方检索数据
final SharePreferences _prefs = await SharedPreferences.getInstance();
String _userString = _prefs.getString("user");
final User _user = User.fromMap(json.decode(_userString));
答案 1 :(得分:0)
在获取数据时使用await关键字对我有用。
await Network.fetch("Bearer " + sharedPreferences.getString("token"),
AuthUtils.endPointProfile);
}
}