skip to Main Content

I have an async class that fetch token from Flutter Secure Storage

  readSecureData(String key) async {
    String? data = await storage.read(key: key);
    print('data from secure storage: $data');
    return "asdasd";
  }

and I fetch the token with then method and store it in a variable token through a dio factory class as follows

class DioFactory {
  //not to have instance
  // ApiService._();
  final FlutterSecureStorage storage = const FlutterSecureStorage();

          static Dio? dio;
    
      Dio getDio() {
        if (dio == null) {
          String? token = "";

     SecureStorage()
          .readSecureData("login_token")
          .then((value) => token = value);

      print("----------------dio");
      print(token);
      print("----------------dio");

      var headers = {
        'Authorization': "Bearer ${token ?? ''}"
      };

      BaseOptions options = BaseOptions(
        baseUrl: ApiConst.apiBaseUrl,
        headers: headers,
      );

      dio = Dio(options);
      return dio!;
    } else {
      return dio!;
    }
  }

but the token is always returned empty although there is a token and I can see the token is printed in readSecureData function, so how can i fetch the token from readSecureData and store it in the token to send it it the dio header

2

Answers


  1.   void anyFunction() {
        String? anyValue;
        Future.delayed(Durations.long1, () {
          return 'anyString';
        }).then((value) {
          anyValue = value;
        });
    
        print(anyValue);
      }
    

    Look, here is a function that contains an async operation but is not defined as Future.

    The output of this function is as follows:

    flutter: null
    

    Because the assignment process takes place without waiting for the Future.delay process.


    This is a function defined as Future and it does the same job.

      Future<void> anyFunction() async {
        String? anyValue;
        await Future.delayed(Durations.long1, () {
          return 'anyString';
        }).then((value) {
          anyValue = value;
        });
    
        print(anyValue);
      }
    

    And here this output:

    flutter: anyString
    

    Did you understand ?

    You have use this way :

     Future<Dio> getDio() async{
            if (dio == null) {
              String? token = "";
    
       await  SecureStorage()
              .readSecureData("login_token")
              .then((value) => token = value);
    
          print("----------------dio");
          print(token);
          print("----------------dio");
    
          var headers = {
            'Authorization': "Bearer ${token ?? ''}"
          };
    
          BaseOptions options = BaseOptions(
            baseUrl: ApiConst.apiBaseUrl,
            headers: headers,
          );
    
          dio = Dio(options);
          return dio!;
        } else {
          return dio!;
        }
    
    Login or Signup to reply.
  2. Future<String>: This function returns a Future that resolves to a String. This indicates that the operation is asynchronous, and when the data is ready, it will be a string.

    async: This keyword is used to mark the function as asynchronous, allowing the use of await inside the function.

    So, first, add Future<String> before readSecureData() method.

      Fture<String> readSecureData(String key) async {
        String? data = await storage.read(key: key);
        print('data from secure storage: $data');
        return "asdasd";
      }
    

    And then get data from readSecureData() using the following snippets.

    String token = await SecureStorage()
              .readSecureData("login_token");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search