首页 > 解决方案 > 在flutter中编写http post请求的方法

问题描述

我正在编写一个用于酒店注册的应用程序,我正在发送如下的帖子请求

checkNetworkConnection只是检查设备上是否有活动连接,如果它是真的,那么我正在调用postFormData方法

Future<dynamic> checkNetworkConnection() async {
    try {
      final result = await InternetAddress.lookup("www.google.com");
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        postFormData().then((val) {
          if (jsonDecode(val.body)[0]["response"] == "false") {
            setState(() {
              isLoading = false;
              //isAbsorbing = false;
            });
            print(val.body);
            print("something went wrong");
            showDialog(
              context: context,
              builder: (_) => new AlertDialog(
                title: Text("hello"),
                content: Text("something went wrong"),
              ),
            );
          } else if (jsonDecode(val.body)[0]["response"] == "true") {
            setState(() {
              isLoading = false;
              //isAbsorbing = false;
            });
            print(val.body);
            print("hotel added successfully");
            showDialog(
                context: context,
                builder: (_) => new AlertDialog(
                      title: Text("Hotel Added Successfully"),
                      content: Text("Hey there! Welcome to j1"),
                    ));
          }
        }).catchError((error) {
          setState(() {
            isLoading = false;
          });
          showDialog(
              context: context,
              builder: (_) {
                return new AlertDialog(
                    title: Text("error!"), content: Text(error.toString()));
              });
        });
      }
    } on SocketException catch (_) {
      setState(() {
        isLoading = false;
      });
      showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                title: Text(
                  "Connection Error !",
                  style: TextStyle(
                      color: Colors.redAccent, fontWeight: FontWeight.bold),
                ),
                content: Text("Check your internet connection !"),
              ));
    }
  }

postFormData方法如下

  Future<dynamic> postFormData() async {
      //there are declarations for parent and headers I just excluded them because they were quite a lot ^_^ !
      final response = await http
        .post("https://thej1.app/apiDataReq",
            body: parent, headers: httpHeaders)
        .then((val) => val)
        .timeout(Duration(seconds: 5))
        .catchError((_) {
      setState(() {
        isLoading = false;
      });
      showDialog(
          context: context,
          builder: (_) =>
              new AlertDialog(title: Text("error"), content: Text("error")));
    });
    return response;
  }

还有其他做同样的事情吗?和未来的建设者一样?

我的响应主体有一个结构,以便我可以创建响应模型。但我无法在未来的构建器中实现它。我也想要捕获异常和超时错误。

提前致谢

标签: flutterdarthttp-post

解决方案


推荐阅读