Home > Enterprise >  How get class object keys in flutter
How get class object keys in flutter

Time:02-04

I created one class as Student.

class Student{
  int id;
  String name;

  Student({this.id,this.name});
}

Now I need to print key - id and name

CodePudding user response:

class Student {
    int id;
    String name;
    String other;
   
    Student(this.id, this.name, this.other);

    getSomeProperties (){
      return{
        'id': id, 'name': name
      };
    }
}

void main() {  
 final test = Student(1,'myName','myOther'); 
 print(test.getSomeProperties());  
}

CodePudding user response:

Create a toJson method inside your Student class, and print out your parameters.

class Student{
  int id;
  String name;

  Student({this.id,this.name});

  Map<String, dynamic> toJson() => {
       if(id!= null) "Id": id,
       if(name != null)  "Name": name,
      };
}

then,

Student exampleStudent= Student(id: '001', name: "john"); //feed values
  print(exampleStudent.toJson());
  • Related