简体   繁体   中英

Question : Dart/Flutter passing parameters not working

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?

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.

you need construct inside the User class.

Example:

class User {
  String? name;
  String? address;
  int? age;
  User({this.name, this.address, this.age});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM