post method

Future post(
  1. BuildContext? context,
  2. String url, {
  3. Map? headers,
  4. dynamic body,
  5. dynamic encoding,
  6. Function? noNetworkCallBack,
  7. Function? sessionExpiredCallback,
})

Implementation

Future<dynamic> post(BuildContext? context, String url,
    {Map? headers,
    body,
    encoding,
    Function? noNetworkCallBack,
    Function? sessionExpiredCallback}) async {
  try {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
      this.context = context;
      log('###########################net post...body....$body');
      return http
          .post(Uri.parse(url),
              body: body,
              headers: headers as Map<String, String>?,
              encoding: encoding)
          .then((http.Response response) async {
        final String res = response.body;
        final int statusCode = response.statusCode;
        log('res#####################  $url##################$res statusCode####################### $statusCode');
        final body = jsonDecode(response.body);
        String? stCode = body["statusCode"];
        if (statusCode == 401 || statusCode == 500) {
          if (sessionExpiredCallback != null) {
            sessionExpiredCallback(context);
          }
          // throw Exception("Session Expired!");
          // prefs = await SharedPreferences.getInstance();
          //
          // Utility().showToast(
          //     "Session is Expired", context, AppColors.information);
          // await prefs.clear();

          // SchedulerBinding.instance.addPostFrameCallback((_) {
          //   Navigator.of(context).pushAndRemoveUntil(
          //       MaterialPageRoute(
          //           builder: (ctx) => Home(
          //             isSessionExpire: true,
          //           )),
          //           (Route<dynamic> route) => false);
          // });
        } else if (stCode != null && stCode.startsWith("F")) {
          throw Exception("Something is wrong !! please try later");
        } else if (statusCode < 200) {
          throw Exception(_decoder.convert(res)['error']['message']);
        } else if (statusCode >= 400) {
          throw Exception("Something Went Wrong!!");
        }
        return res;
      }).catchError((onError) {
        log(onError.toString());
        if (onError.toString().toLowerCase().contains("timeout")) {
          throw Exception("Server timeout");
        } else {
          throw Exception("Something Went Wrong!!");
        }
      });
    }
  } on SocketException catch (_) {
    if (noNetworkCallBack != null) {
      noNetworkCallBack();
    }
    Utility().showToast("No Internet", context, AppColors.information);
    throw Exception("No Internet");
  }
}