Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a POST request in a flutter for web API

Tags:

http

flutter

I try writing a common POST request method but it's getting below error

Future<dynamic> requestMethod() async {
  var url = "https://testurl";
  var body = json.encode({"program_id":"1211"});

  Map headers = {
    'Content-type' : 'application/json',
    'Accept': 'application/json',
  };

  var response =await http.post(url, body: body, headers: headers);
  final responseJson = json.decode(response.body);
  print(responseJson);
  return response;
}

Error

Unhandled exception: E/flutter (24453): type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>' E/flutter (24453): #0 NetworkUtil.requestMethod (package:fitnessstudio/globals.dart:76:61) E/flutter (24453): <asynchronous suspension>
like image 685
pradip koravi Avatar asked Jul 16 '18 13:07

pradip koravi


1 Answers

I solved the problem by using following code

     Future<dynamic> post(String url,var body)async{
        return await http
            .post(Uri.encodeFull(url), body: body, headers: {"Accept":"application/json"})
            .then((http.Response response) {
    //      print(response.body);
          final int statusCode = response.statusCode;
          if (statusCode < 200 || statusCode > 400 || json == null) {
            throw new Exception("Error while fetching data");
          }
          return _decoder.convert(response.body);
        });
      }
like image 120
pradip koravi Avatar answered Nov 15 '22 00:11

pradip koravi