Sorry if my question is stupid, but I am studying it by myself and don't have many 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 paramemter?
CodePudding user response:
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.
CodePudding user response:
you need construct inside the User
class.
Example:
class User {
String? name;
String? address;
int? age;
User({this.name, this.address, this.age});
}