[英]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.我想把一个map改成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.我试着按照https://docs.flutter.dev/development/data-and-backend/json#creating-model-classes-the-json_serializable-way这个例子,但它没有像我预期的那样工作。
assume that the class I am using is假设我使用的 class 是
class User {
String? name;
}
User({name});
and I have a json as String userJson = {"name":"Dart"}
我有一个 json 作为String userJson = {"name":"Dart"}
I tried to decode the json to a Map and change that to User instance.我试图将 json 解码为 Map 并将其更改为 User 实例。
When I do print(userJson["name"])
it prints "Dart", but then if I put that into the user class当我执行print(userJson["name"])
时,它会打印“Dart”,但是如果我将其放入用户 class
User user = User(name: value);
print(user.name);
it prints null.它打印出 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?正如我之前所说,为什么我不能将“name”值传递给 User 参数?
Use this.name
in the constructor instead.在构造函数中使用this.name
代替。
Like so:像这样:
class User {
String? name;
User({this.name});
}
Without this.
没有this.
, the name
from the constructor, is different from the name
in the class. ,来自构造函数的name
,与 class 中的name
不同。
you need construct inside the User
class.您需要在User
class 内部构建。
Example:例子:
class User {
String? name;
String? address;
int? age;
User({this.name, this.address, this.age});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.