Flutter jsonDecode return type is `dynamic` whereas Album factory method expects a `Map<String, dynamic>`

Viewed 685
import 'dart:convert';

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

part 'http.g.dart';

@JsonSerializable()
class Album {
  final int userId;
  final int id;
  final String title;

  Album({this.userId, this.id, this.title});

  factory Album.fromJson(Map<String, dynamic> json) => _$AlbumFromJson(json);
  Map<String, dynamic> toJson() => _$AlbumToJson(this);
}

Future<Album> fetchAlbum() async {
  var resp = await http.get('https://jsonplaceholder.typicode.com/albums/1');
  var A = Album.fromJson(jsonDecode(resp.body)); // Error line

  print(A.title);
  print(A.toJson());
}

Error - At var A = Album.fromJson(jsonDecode(resp.body)); is The argument type 'dynamic' can't be assigned to the parameter type 'Map<String, dynamic>'.dartargument_type_not_assignable.

jsonDecode return type is dynamic whereas Album factory method expects a Map<String, dynamic>.

It shows compile-time error but I am able to get desired outputs in debug console.

How should we solve this?

3 Answers

Adding @Ulas's comment as an answer here -

We can use as keyword with jsonDecode for it to return a specific type rather that dynamic -

var A = Album.fromJson(jsonDecode(resp.body) as Map<String, dynamic>);

You are getting that problem since jsonDecode returns a dynamic type. You'd have to convert that dynamic type to a Map<String,dynamic>.

Instead of:

Album.fromJson(jsonDecode(resp.body));

Do this:

Album.fromJson(Map<String,dynamic>.from(jsonDecode(resp.body)));
var A = Album.fromJson(jsonDecode(resp.body as Map<String, dynamic>)); // no error

Add some try-catch blocks. Allot of stuff could go wrong when you send a request :)

Related