Home > OS >  type 'String' is not a subtype of type 'Map<String, UserNote>' in type cas
type 'String' is not a subtype of type 'Map<String, UserNote>' in type cas

Time:04-28

In order to make an HTTP request using Post method, I've created a method called AddNotes as shown below:


 Future<void> addNotes(UserNote userNote) async{
    String url = "dashboard/user_notes/";
     try {
         final response = await Api.Post(
           url: url, 
        body: json.encode({
                 'display_id': userNote.display_id,
                  'note': userNote.note,
                  'created_at': Tracker.encode(userNote.created_at!),
                   'updated_at': Tracker.encode(userNote.updated_at!),
          }) as Map<String, dynamic>
          );
            print(response.body);

          final newNote = UserNote(
            id: userNote.id,
            display_id: userNote.display_id,
             note: userNote.note,
             created_at: userNote.created_at,
             updated_at: userNote.updated_at);
             notesList.add(newNote);
                 notifyListeners();  
     } catch (e) {
        print("error loading notes");
        print(e.toString());
     }
 }

When I tried to print the response on the console, I got the following error :

type 'String' is not a subtype of type 'Map<dynamic, dynamic>' in type cast

Anyone have an idea where is the problem?

CodePudding user response:

When you use json.encode(), the method will return a string with a json parsed.

Imagine your json like this:

{
  "foo": "bar"
  "hello": 1
}

When you encode, your result will be a string like that: '{"foo":"bar","hello":1}'

So, you don't need to use as Map<String, dynamic> in your body.

CodePudding user response:

If you check runtimeType of json.encode() it shows String type and you cannot cast it to Map<String,dynamic>.

var object = {
                 'display_id': userNote.display_id,
                 'note': userNote.note,
                 'created_at': Tracker.encode(userNote.created_at!),
                 'updated_at': Tracker.encode(userNote.updated_at!),
          };

var jEncode = json.encode(object);
// you can cast it directly
var map = object as Map<String,dynamic>;
// if you decode then cast to Map from encode result
var jToMap = json.decode(jEncode) as Map<String,dynamic>;

print(jEncode.runtimeType);
print(map.runtimeType);
print(jToMap.runtimeType);

results

String
_JsonMap
JsLinkedHashMap<String, dynamic>

  • Related