Home > Net >  The argument type 'dynamic' can't be assigned to the parameter type 'Map<Stri
The argument type 'dynamic' can't be assigned to the parameter type 'Map<Stri

Time:12-15

final dataResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
    Album.fromJson(jsonDecode(dataResponse.body));

On nullsafety enabled project, Album.fromJson(jsonDecode(dataResponse.body)); this code throwing error The argument type 'dynamic' can't be assigned to the parameter type 'Map<String, dynamic>'.

Followed official doc

Following code used for data modeling.

class Album {
  final int userId;
  final int id;
  final String title;

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

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

CodePudding user response:

You just need to cast your jsonDecode

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

to explicit type:

Album.fromJson(jsonDecode(dataResponse.body) as Map<String, dynamic>);

CodePudding user response:

Just you need to change (Map<String, dynamic> json) to (dynamic json)

factory Album.fromJson(dynamic json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }

CodePudding user response:

The model is already good...

Try this.

final dataResponse = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
List<dynamic> list =jsonDecode(dataResponse.body);
return list.map((e)=>Album.fromJson(e)).toList();
  • Related