Here's the simplifed code to show what I'm trying to achieve:
class MyClass {
MyClass() {
authorize();
}
String? token;
void authorize() async {
final response =
await Future<String>.delayed(Duration(seconds: 1), (() => "14dw65d1q"));
token = response;
print('Token: $token');
}
String printToken() {
return 'Token: $token';
}
}
void main() {
final myClass = MyClass();
print(myClass.printToken());
}
Basically I'm trying to use token
(whose default value of null
is changed by authorize()
) in another function. The output is:
Token: null
Token: 14dw65d1q
Apparently, main()
runs before the value of token gets assigned. Thus, I get a 401 error when I try to use token
in the header of a network request. (Not shown in code) How can I make printToken()
run after the value of token
gets assigned? Making main()
async and/or awaiting myClass.printToken()
doesn't work. I get 'await' applied to 'String', which is not a 'Future'.
when I await 'Token: $token'
or myClass.printToken()
anyway.