I have an async class that fetch token from Flutter Secure Storage
readSecureData(String key) async {
String? data = await storage.read(key: key);
print('data from secure storage: $data');
return "asdasd";
}
and I fetch the token with then method and store it in a variable token through a dio factory class as follows
class DioFactory {
//not to have instance
// ApiService._();
final FlutterSecureStorage storage = const FlutterSecureStorage();
static Dio? dio;
Dio getDio() {
if (dio == null) {
String? token = "";
SecureStorage()
.readSecureData("login_token")
.then((value) => token = value);
print("----------------dio");
print(token);
print("----------------dio");
var headers = {
'Authorization': "Bearer ${token ?? ''}"
};
BaseOptions options = BaseOptions(
baseUrl: ApiConst.apiBaseUrl,
headers: headers,
);
dio = Dio(options);
return dio!;
} else {
return dio!;
}
}
but the token is always returned empty although there is a token and I can see the token is printed in readSecureData function, so how can i fetch the token from readSecureData and store it in the token to send it it the dio header
2
Answers
Look, here is a function that contains an async operation but is not defined as Future.
The output of this function is as follows:
Because the assignment process takes place without waiting for the Future.delay process.
This is a function defined as Future and it does the same job.
And here this output:
Did you understand ?
You have use this way :
Future<String>:
Thisfunction
returns a Future that resolves to a String. This indicates that the operation is asynchronous, and when the data is ready, it will be a string.async:
This keyword is used to mark thefunction
as asynchronous, allowing the use ofawait
inside thefunction
.So, first, add
Future<String>
beforereadSecureData()
method.And then get data from
readSecureData()
using the following snippets.