I am using Laravel for my back end and Flutter for my front end.
When the token is stored, I use my local storage:
localStorage.setString('token',json.encode(body['access_token']));
This works fine. The token is stored as expected. But when I try to get it back from localStorage
using:
token = localStorage.getString('token');
Then the token will be returned in the following format:
> \"eyJ0eXAiOiJKV1[...]a0\"
where the backslash located in the start and finish of the token which were NOT supposed to be there.
How can I remove them before using it for a call on my backend?
However, before the store event, I use DebugPrint() to "see" that the token is returned from my call to Laravel.
With debugPrint(), I get the proper result of the token which looks like :
>"eyJ0eXAiOiJ[...]|"
CodePudding user response:
But if you need to remove last and first elements on your String, try this,
String token = "\eyJ0\";
List<String> list = token.split(""); // ['\', 'e', 'y', 'j', '0', '\']
list.removeAt(0); // ['e', 'y', 'j', '0', '\']
list.removeLast(); // ['e', 'y', 'j', '0']
final String backslashRemovedToken = list.join();
CodePudding user response:
You can follow this for token store and retrieve it from local storage.
static Future<SharedPreferences> getSharedPref() async {
return await SharedPreferences.getInstance();
}
static saveToken(String token) async {
await getSharedPref().then((SharedPreferences pref) {
pref.setString("token", token);
print("saving token $token");
});
getToken();
}
static Future<String> getToken() async {
return await getSharedPref().then((SharedPreferences pref) {
String token = pref.getString("token");
// print("getting token $token");
return token;
});
}
final accessToken = await PreferenceManager.getToken();
N.B: don't forget to use async and await