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

Time:04-08

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();

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

CodePudding user response:

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


CodePudding user response:

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


}

CodePudding user response:

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

  • Related