skip to Main Content

Here is my code:

Map<String, dynamic>? myMap = {
‘conversationId’: iD,
‘type’: ‘text’,
‘data’: _controller.text.toString(),
‘msgLength’:_controller.text.length,
‘senderId’: Provider.of( context,listen: false).id,
‘createdOn’: 190823,
‘messageState’: ‘delivered’,
‘isDeleted’: 0,
‘id’: 3048,
};

          String encoded = json.encode(myMap);

     // Make the POST request and wait for the response
     final response = await postRequest(url: conversationUrl,
                                        body: encoded,
                                        headers:{'Content-Type': 'application/json'},);

BUT I AM SHOWN a RED LINE UNDER encoded in the body parameter, with the error: The argument type ‘String’ can’t be assigned to the parameter type ‘Map<String, dynamic>?’

I have tried (Dart HTTP POST with Map<String, dynamic> as body) changes, now what?

2

Answers


  1. So what I think might be happening is an issue in the way the json is being encoded, maybe

    We usually do

    body: jsonEncode(<String, String> {
            'key1':'value1', //hard coded
            'key2': 'value2',
            'key3': variable, //for variables given to the post function in the repository
            'boolean_key': booleanVar ? "True": "False", //for boolean variables
          }
          )
    

    Also, the docs for json encode say this:

    Shorthand for json.encode. Useful if a local variable shadows the global json constant.
    Example:
    const data = {'text': 'foo', 'value': 2, 'status': false, 'extra': null};
    final String jsonString = jsonEncode(data);
    print(jsonString); // {"text":"foo","value":2,"status":false,"extra":null}
    

    Try making the String encoded of type final

    Login or Signup to reply.
  2. The body takes the map, not the encoded string. Simply use

    body: myMap,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search