1

Using flutter docs am trying to learn json deserialization. But I am getting the following error "The argument type 'Map<String, String>' can't be assigned to the parameter type 'String'"

heres the code

import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));




void main() {
    
  var jsonString = {
  "name": "Martin Perumala",
  "email": "martinarxxxxx@gmail.com"
};

User user = User.fromJson(jsonDecode(jsonString) as Map<String,dynamic>);

}

class User {
    User({
        required this.name,
        required this.email,
    });

    String name;
    String email;

    factory User.fromJson(Map<String, dynamic> json) => User(
        name: json["name"],
        email: json["email"],
    );

   
}

1 Answers1

0

You are trying to decode something that is already a Map!

in your example you don't need to decode:

  User user = User.fromJson(jsonString);

or you decode a string

  var jsonString =
      '{"name": "Martin Perumala","email": "martinarxxxxx@gmail.com"}';

  User user = User.fromJson(jsonDecode(jsonString));
cabbi
  • 393
  • 2
  • 12
  • If you want a "smart" way to encode and decode classed take a look to https://pub.dev/packages/jsonize – cabbi Jul 01 '23 at 05:52