Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign future<String> to a String variable in flutter

Tags:

flutter

dart

So basically I have a Future which return the jwt I got from secure storage, and I want to assign the return to a variable let's say the variable is token. It goes kind of something like this.

Future<String> getJwt() async {
      final secureStorage = SecureStorage();
      var jwt = await secureStorage.readSecureData('jwt');
      return jwt;
    }

and I want to assign to variable, like this.

static String token = getJwt();

the code is something like this.

String? _token;

Future<String> getJwt() async {
      final secureStorage = SecureStorage();
      var jwt = await secureStorage.readSecureData('jwt');
      return jwt;
    }

void getJWT() async {
  String token = await getJwt(); 
  
}

class API {

  final token = getJWT();
  static Future<String> getData(String url) async {
    try {
      http.Response response = await http.get(Uri.parse(baseURL + url),
          headers: {
            "Content-type": "application/json",
            "Authorization": 'Bearer ' + token
          });

      return response.body;
    } catch (_) {
      return 'error';
    }
  }

  static Future<String> postData(String url, String json) async {
    try {
      http.Response response = await http.post(Uri.parse(baseURL + url),
          headers: {
            "Content-type": "application/json",
            'Authorization': 'Bearer ' + token
          },
          body: json);

      return response.body;
    } catch (_) {
      return 'error';
    }
  }
}

I already try changing the String to Future but It doesn't work, how to solve this problem? thanks in advance.

like image 925
Adzf Avatar asked May 13 '26 23:05

Adzf


1 Answers

So you need an asynchronous function to do this. I know of 2 ways:

  1. use async/await
  2. use then

Example:

// use async await
void main() async {
  String ret = await getAbc();
  print("ret: $ret");
  // ----- result -----
  // ret: abc
}

// use then
void main2() {
  getAbc().then((String ret) {
    print("ret: $ret");
  });
  // ----- result -----
  // ret: abc
}

Future<String> getAbc() async {
  await Future.delayed(Duration(seconds: 1));
  return "abc";
}


like image 180
Tuan Avatar answered May 16 '26 15:05

Tuan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!