Search code examples
androidflutterdartpostmanhttp-post

how to use POST method in dart?


I want to send a request to server and get details, i have written some code but i don't know why it doesn't work. i found out that the reason is that the my variables won't be sent to server and i don't know where is problem. here is my codes :

  _sendBuyBtnReq(
      {required BuildContext context,
      required String Amount,
      required String ScoreAmount}) async {
    final prefs = await SharedPreferences.getInstance();
    var toke = prefs.getString('mykey');
    var ide = prefs.getString('mykey');

    final url = Uri.parse('my url');
    var body = Map<String, dynamic>();

    body["CustomerId"] = '$ide';
    body["Amount"] = '$Amount';
    body["Credit"] = '$ScoreAmount';
    body["Description"] = '2';

    http.Response response = await http.post(
      url,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Authorization': 'Bearer $toke'
      },
    );

    if (response.statusCode == 200) {
      print(await response.body.toString());
    } else {
      print(response.reasonPhrase);
      var messageM = jsonDecode(utf8.decode(response.bodyBytes));
      var MessageModel = messageModel(messageM['message']);
      // print(MessageModel._message);
      showSnackBar7(context, MessageModel.message);
    }
  }

Solution

  • You must pass body to the request

    and make sure your url is working

    try this

        final prefs = await SharedPreferences.getInstance();
        var toke = prefs.getString('mykey');
        var ide = prefs.getString('mykey');
        final url = Uri.parse('my url'); //pass proper url
        var body = Map<String, dynamic>();
        
        body["CustomerId"] = '$ide';
        body["Amount"] = '$Amount';
        body["Credit"] = '$ScoreAmount';
        body["Description"] = '2';
    
        http.Response response = await http.post(
              url,
              headers: {
                'Content-Type': 'application/json; charset=UTF-8',
                'Authorization': 'Bearer $toke'
              },
             body: body,
            );
    
    
        if (response.statusCode == 200) {
           print(response.body.toString());
        }