【问题标题】:how create future function in flutter?如何在颤振中创建未来功能?
【发布时间】:2021-09-19 19:30:18
【问题描述】:

我试图在颤振中创建帖子功能 这是我的代码:

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

但我收到了这个错误: 主体可能正常完成,导致返回“null”,但返回类型可能是不可为空的类型。 尝试在 end.dart(body_might_complete_normally) 处添加 return 或 throw 语句 我该怎么办?

【问题讨论】:

    标签: flutter asynchronous flutter-android flutter-future


    【解决方案1】:

    使用if (error.toString() != "[]") 行,您将您的功能划分为 2 个可能的结果。

    正面的,没有return

    也许您应该将return requestResult; 移动到大括号之后,这样无论如何都会触发返回。

    【讨论】:

      【解决方案2】:

      你缺少 if 条件中的 return 语句

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

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 2021-12-27
        • 2020-09-25
        • 2021-10-12
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 2021-02-25
        • 2021-11-24
        相关资源
        最近更新 更多