How To Make Post To A External API With Methods And Data By Dart

2,645

Solution 1

For REST API calls I prefer to use a library named Dio. Its way too easy to make GET, POST, PUT, DELETE etc calls using Dio.

For Example

import 'package:dio/dio.dart';

   //Now like this

void _makeApiCall() async {
   Dio dio = new Dio();
   Response apiResponse = await dio.get('${YOUR URL}?id=$id'); //Where id is just a parameter in GET api call
   print(apiResponse.data.toString());
}

And If you want to make a POST call and you need to send Form data with that do like this

void _makeApiCall() async {
   Dio dio = new Dio();
   FormData formData = FromData.from({
    name : "name",
    password: "your password",
   }); // where name and password are api parameters
   Response apiResponse = await dio.post('${YOUR URL}', data: formData); 
   print(apiResponse.data.toString());
}

Also you can map the received data into so called POJOs for better handling and usage. If you want to know how to map the data into POJO (Objects), Just let me know.

Solution 2

you need to be more specif about the API and what you want to send. this is a simple example from the HTTP client library

import 'package:http/http.dart' as http;

var url = "http://example.com/whatsit/create";
http.post(url, body: {"name": "doodle", "color": "blue"})
    .then((response) {
  print("Response status: ${response.statusCode}");
  print("Response body: ${response.body}");
});

http.read("http://example.com/foobar.txt").then(print);
Share:
2,645
Karim Mohamed
Author by

Karim Mohamed

Karim Mohamed, Software Developer.

Updated on December 06, 2022

Comments

  • Karim Mohamed
    Karim Mohamed over 1 year

    I Have A Web Service And Want To Post Data By Flutter Dart json In My WebService API Link