简体   繁体   中英

How to set flutter POST method using DIO?

This is my code below, i'm stuck please help. How to set flutter POST method using DIO?

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

This method works in http

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

Put this code inside the function

you can create a new function and call this from anywhere:

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

The instance of Dio provide POST method where we can pass param in JOSN format

Performing a POST request:

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

To send the form data, we can use an instance of FormData and pass mapping values of keys and specify where you want to send the data.

Most applications need to send files/images to the server as multipart/form-data and this is extremely easy to achieve with Dio due to all the classes and methods available in the Dio package.

Sending FormData:

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM