I am trying to save device token to SharedPreferences so I can use it in other widgets, but token value is always coming as null in other widgets. Not sure what I am doing wrong here.
@override
void initState() {
// TODO: implement initState
super.initState();
_messaging.getToken().then((token) {
_getAndSaveToken;
});
}
_getAndSaveToken() {
_messaging.getToken().then((token) async{
final prefs = await SharedPreferences.getInstance();
await prefs.setString('token', token);
print(token);
});
}
In order to use shared preferences first you have to create an instance like this
SharedPreferences prefs = await SharedPreferences.getInstance();
Then to save a value
prefs.setString("token", token);
To Access this file in another widget you should access the same instance and use get
String token = prefs.getString("token");
In your case to set the token it should be like this.
_getAndSaveToken() async {
_messaging.getToken().then((token) {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("token", token);
print(token);
});
}
You can access this token like below
_getSavedToken() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString("token"); // do something with this
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.