1

这是我下面的代码,我被卡住了,请帮忙。如何使用 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

4

3 回答 3

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

将此代码放入函数中

于 2020-06-02T17:10:29.917 回答
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');
    }
  }
于 2020-10-27T02:57:59.310 回答
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);
于 2021-04-16T02:55:24.510 回答