Adzf
Adzf

Reputation: 59

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

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.

Upvotes: 3

Views: 6636

Answers (3)

Sahil Hariyani
Sahil Hariyani

Reputation: 1178

Future<String> getJwt() async {}

as getJWT() returns a Future which indicates it will return some value (a String) in the future. This is part of asynchronous programing.

So, adding await basically says that we need to wait for the response which will be there at some point in the future.

static String token = await getJwt();

You can watch this awesome tutorial on async and wait by Flutter team

Upvotes: 0

Tuan
Tuan

Reputation: 2421

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";
}


Upvotes: 6

Rodrigo Molero
Rodrigo Molero

Reputation: 346

Since you are working with Futures, I would recommend you to separate your methods to poblate variables. Also, keep in mind that Future functions require asynchronous notations like this:

Your function

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

Future functions

late String _jwt;

setJwt(String jwt){
  _jwt = jwt;
}

Future<void> poblateJwt () async {
  await getJwt().then((value){
   setJwt(value);
  });
}

getJwtData() {
  return _jwt;
}

Now, you can call the function getJwtData and use it everywhere. The last remaining thing is use a FutureBuilder in your app and call the "poblateJwt" method only once. Like this:

class YourWidget extends StatefulWidget {
  const YourWidget({Key? key};

  @override
  State<YourWidget> createState() => _YourWidgetState();
}

class _YourWidgetState extends State<YourWidget> {
  late var _future;

  @override
  void initState() {
    _future = poblateJwt();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    //use this as a String value

    final jwt = getJwtData();

    return FutureBuilder(
      future: _future,
      ... rest of your  code
    );
  }


}

Upvotes: 0

Related Questions