skip to Main Content

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

2

Answers


  1. 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());
    
    Login or Signup to reply.
  2. For a proper way to do that you could check my code below. This is how to override the toString().

    import 'package:flutter/foundation.dart';
    
    @immutable
    class Student{
      final int id;
      final String name;
    
      const Student({required this.id,required this.name});
    
      @override
      String toString() {
        return 'Student{id: $id, name: $name}';
      }
      
    }
    

    Then you could print like this:

        Student student = const Student(id: 1, name: 'John');
        print(student);
        print(student.id);
        print(student.name);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search