how to delay process

Viewed 86

I am retrying api call if I get 401 response but before completing my retrying process my api call is executing I want to run retry process then only I want to call api following is my api where I am retrying process

Future<void> postvehickes(BuildContext context, String vehicleType) async {
    //print(token);

    var data = {"vehicletype": vehicleType, "filename": vehicleType};
    Map<String, String> obj = {"attributes": json.encode(data).toString()};

    var flutterFunctions =
        Provider.of<FlutterFunctions>(context, listen: false);
    final url = Ninecabsapi().urlHost + Ninecabsapi().getvehicle;
    try {
      final client = await RetryClient(
        http.Client(),
        retries: 1,
        when: (response) {
          return response.statusCode == 401 ? true : false;
        },
        onRetry: (req, res, retryCount)  {
          //print('retry started $token');
          if (retryCount == 0 && res?.statusCode == 401) {
             Provider.of<Auth>(context, listen: false)
                .restoreAccessToken();

            req.headers['Authorization'] = token!;
            print('retry started ${req.headers['Authorization']}');
            //req.headers.clear();

          }
        },
      );
      loading();
      var response = await http.MultipartRequest("POST", Uri.parse(url))
        ..files.add(await http.MultipartFile.fromPath(
            "imagefile", flutterFunctions.imageFile!.path,
            contentType: MediaType("image", "jpg")))
        //..headers['Authorization'] = token!
        ..fields.addAll(obj);

      final send = await client.send(response);
      final res = await http.Response.fromStream(send);
      var messages = json.decode(res.body);
      loading();

      print("this is from postvehicles $messages");
      notifyListeners();
    } catch (e) {
      print(e);
    }
  }

following is my api where I am restoring access token if expires I want to complete the whole process before executing above api

Future<void> restoreAccessToken() async {
    print('restoreAccessToken started');
    final url = '${Ninecabsapi().urlHost}${Ninecabsapi().login}/$sessionId';

    var response = await http.patch(
      Uri.parse(url),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        'Authorization': accessToken!
      },
      body: json.encode(
        {"refresh_token": refreshtoken},
      ),
    );
    var userDetails = json.decode(response.body);

    if (response.statusCode == 401) {
      print(userDetails['messages']);
    }

    print(userDetails);
    sessionId = userDetails['data']['session_id'];
    accessToken = userDetails['data']['access_token'];
    accessTokenExpiryDate = DateTime.now().add(
      Duration(seconds: userDetails['data']['access_token_expiry']),
    );
    refreshToken = userDetails['data']['refresh_token'];
    refreshTokenExpiryDate = DateTime.now().add(
      Duration(seconds: userDetails['data']['refresh_token_expiry']),
    );

    //print(userDetails);

    notifyListeners();
    final prefs = await SharedPreferences.getInstance();
    final userData = json.encode({
      'sessionId': sessionId,
      'refreshToken': refreshToken,
      'refreshExpiry': refreshTokenExpiryDate!.toIso8601String(),
      'accessToken': accessToken,
      'accessTokenExpiry': accessTokenExpiryDate!.toIso8601String()
    });

    prefs.setString('userData', userData);
    reset();
  }

here I had tried async and await to my retry client and I had awaited the restoreAccessToken but the process is not waiting before I implement headers here you can see 2 markings in imagein this image I want white marking response to be top on red marking response

1 Answers

Try removing await from this

final client = await RetryClient(
        http.Client(),
        retries: 1,
        when: (response) {
          return response.statusCode == 401 ? true : false;
        },
        onRetry: (req, res, retryCount) async {
          //print('retry started $token');
          if (retryCount == 0 && res?.statusCode == 401) {
            await Provider.of<Auth>(context, listen: false)
                .restoreAccessToken();

            req.headers['Authorization'] = token!;
            print('retry started ${req.headers['Authorization']}');
            //req.headers.clear();

          }
        },
      );

change the above code to

final client = RetryClient(
        http.Client(),
        retries: 1,
        when: (response) {
          return response.statusCode == 401 ? true : false;
        },
        onRetry: (req, res, retryCount) async {
          //print('retry started $token');
          if (retryCount == 0 && res?.statusCode == 401) {
            await Provider.of<Auth>(context, listen: false)
                .restoreAccessToken();

            req.headers['Authorization'] = token!;
            print('retry started ${req.headers['Authorization']}');
            //req.headers.clear();

          }
        },
      );
Related