0

i trying to create post function in flutter here is my code:

  Future<String> makePostRequest() async {
    String requestResult;
    var body = this.toMapRequest();
    String requestUrl = RequestZarinpal.PAYMENT_REQUEST_URL;
    String gateWayUrl;
    String jsonBody = json.encode(body);
    final encoding = Encoding.getByName('utf-8');

    Response response = await post(
      requestUrl,
      headers: headers,
      body: jsonBody,
      encoding: encoding,
    ).timeout(const Duration(seconds: 10), onTimeout: () {
      throw TimeoutException('The connection has timed out, Please try again!');
    });

    responseBody = response.body;
    var parsedJson = json.decode(responseBody);
    var data = parsedJson['data'];
    var error = parsedJson['errors'];
    if (error.toString() != "[]") {
      var errorcode = parsedJson['errors']['code'];
      print("$body   va  $requestUrl va $parsedJson");
      requestResult = "   شما ارور زیر را دریافت کرده اید \n$error";
    } else if (data.toString() != "[]") {
      var authority = parsedJson['data']['authority'];
      requestResult = "اتوریتی شما با موفقیت ساخته شد و به درگاه متصل می شود";
      _request.setAuthority(authority);
      print(parsedJson);

      String gateWay = RequestZarinpal.PAYMENT_GATEWAY_URL;
      gateWayUrl = "$gateWay$authority";

      if (await canLaunch(gateWayUrl)) {
        await launch(
          gateWayUrl,
          forceSafariVC: false,
          forceWebView: false,
          headers: headers,
        );
      } else {
        throw 'Could not launch $requestUrl';
      }

      print(requestResult);

      return requestResult;
    }
  }

but i got this error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type. Try adding either a return or a throw statement at the end.dart(body_might_complete_normally) what should i do?

asal rad
  • 43
  • 1
  • 5

2 Answers2

0

With the line if (error.toString() != "[]") you divided your function in 2 possibile outcome.

The positive one, doesn't have a return.

Maybe you should move return requestResult; after the curly bracket, so that the return gets fired regardless.

L. Gangemi
  • 3,110
  • 1
  • 22
  • 47
0

You are missing the return statement inside the if condition

if (error.toString() != "[]") {
  var errorcode = parsedJson['errors']['code'];
  print("$body   va  $requestUrl va $parsedJson");
  requestResult = "   شما ارور زیر را دریافت کرده اید \n$error";

  return requestResult;
}
t00n
  • 395
  • 5
  • 12