如何使用DIO设置颤振POST方法?

时间:2020-06-02 15:44:34

标签: flutter dart dio

这是我下面的代码,我被卡住了,请帮助。如何使用DIO设置颤振POST方法?

Map<String, dynamic> toJson() {
    return {
        'id': id,
         "name": name,
         "telNumber": telNumber,
         "email": email,
         "age": age
      };
   }

String postToJson(Post data){
      final dyn = data.toJson();
      return json.encode(dyn);
}

Future<http.Response> createPost(Post post) async {
          final response = await http.post(
               "$baseUrl/users",
              headers: {
                  "content-type": "application"
                    },
              body: postToJson(post));
              return response;
            }

此方法适用于http

3 个答案:

答案 0 :(得分:1)

 BaseOptions options = new BaseOptions(
     baseUrl: $baseUrl,
     connectTimeout: 10000,
     receiveTimeout: 10000,);
final dioClient = Dio(options);
try{
   final response = await dioClient.post("/users", data: FormData.fromMap(
      postToJson(post))
    ),);
   return response;
} catch (e) {
  throw (e);
}

将此代码放入函数中

答案 1 :(得分:0)

您可以创建一个新函数并在任何地方调用它:

Future<Null> SendPost() async {

    Response response;
    BaseOptions options = new BaseOptions(
      baseUrl: "https://your.url",
      connectTimeout: 6000,
      receiveTimeout: 3000,
    );
    Dio dio = new Dio(options);

    FormData formData = new FormData.fromMap({
      "post_data1": value,
      "post_data2": value,
    });

    try {
      response=await  dio.post("/page.php", data: formData);
      return response;
    } catch (e) {
      print('Error: $e');
    }
  }

答案 2 :(得分:0)

Dio 的实例提供了 POST 方法,我们可以在其中以 JOSN 格式传递参数

执行 POST 请求:

Dio dio = Dio();

void postHTTP(String url, Map data) async {
  try {
    Response response = await dio.post(url, data: data);
    // Do whatever
  } on DioError catch (e) {
    // Do whatever
  }
}

要发送表单数据,我们可以使用 FormData 的实例并传递键的映射值并指定要将数据发送到何处。

大多数应用程序都需要将 files/images 作为 multipart/form-data 发送到服务器,由于 Dio 包中提供了所有可用的类和方法,因此使用 Dio 非常容易实现这一点。

发送表单数据:

// Single File with Additional Data
FormData formData = FormData.fromMap({
  "name": "Ryan Dsilva",
  "age": 21,
  "file": await MultipartFile.fromFile("PATH", filename:"OPTIONAL"),
});

// Multiple Files with Additional Data
FormData formData = FormData.fromMap({
  "name": "Ryan Dsilva",
  "age": 21,
  "files": [
    await MultipartFile.fromFile("PATH", filename:"OPTIONAL"),
    MultipartFile.fromFileSync("PATH", filename:"OPTIONAL")
  ],
}); 

var response = await dio.post('/info', data: formData);