Question : Dart/Flutter passing parameters not working

Issue

Sorry if my question is stupid, but I am studying it by myself and don’t have much experience. 🙂 thanks for your help!

I wanted to change a map to JSON.

I tried to follow https://docs.flutter.dev/development/data-and-backend/json#creating-model-classes-the-json_serializable-way this example, but it is not working as I expected.

assume that the class I am using is

class User {
   String? name;
}

User({name});

and I have a json as String userJson = {"name":"Dart"}

I tried to decode the json to a Map and change that to User instance.

When I do print(userJson["name"]) it prints "Dart", but then if I put that into the user class

User user = User(name: value);
print(user.name);

it prints null.

Why is the value not saved into user?

When I pass the value as

User.fromJson(Map<String, dynamic> json) {
   name = json["name"];
}

User user = User.fromJson(map);
print(user.name);

then of course it works well.

as I said before,
why can’t I pass the "name" value to the User parameter?

Solution

Use this.name in the constructor instead.

Like so:

class User {
  String? name;
  User({this.name});
}

Without this., the name from the constructor, is different from the name in the class.

Answered By – Josteve

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *