Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

flutter - how to achieve object literals in dart

I have a class which has named constructor and I want to pass variable and eval the result as a class variable how can I achieve it like in javascript we have object literals and eval
I'm getting the data from server like [{path: 'fullName', msg: "Field is Required" }, {...}]

below is the example:

class Test{
   String fullName;
   
   Test({this.fullName});

}

Map ob = {fullName: "someAnotherName", another:another};
var t = Test(ob); //how to achieve this line

var varaible = "fullName";
t.[variable]; //how to achieve this line
`
question from:https://stackoverflow.com/questions/65933989/how-to-achieve-object-literals-in-dart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is common to write a named fromJson factory constructor which accpets a Map<String, dyanmic> as an argument which is the json data you will pass to it. For the code you provided it would be like:

class Test{
   String fullName;
   
   Test({this.fullName});

   factory Test.fromJson(Map<String, dynamic> json) {
      return Test(
         fullName: json['fullName'],
      );
   }
}

Map ob = {fullName: "someAnotherName", another:another};
var t = Test.fromJson(ob);
t.fullName;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...