Edoardo
Edoardo

Reputation: 9

Why variable token is null?

i am writing this dart code but i've a problem with assignment value to "token".

String? token;
loadJson().then((response) {
    token = response;
});

print(token); //Print null

Thanks!

Upvotes: 0

Views: 169

Answers (2)

Anas Nadeem
Anas Nadeem

Reputation: 897

print the token in the then function:

String? token;
loadJson().then((response) {
    token = response;
    print(token);
});

Or use await:

String? token;
var response = await loadJson();
token = response;
print(token);

Upvotes: 2

Antoniossss
Antoniossss

Reputation: 32535

Becuase your code is kind of equal to

String? token;

print(token); //Print null
///sleeep some time
token = loadJson();

Upvotes: 1

Related Questions