skip to Main Content

I have a list of names.

I have a class with name details like name, age, and height.

I need to create a list of names and add to the list all the details.

I am not seeing any data. Instead, I see: mylist is instance of.

Could you please advise how to address this issue.

Thank You

My code:

PeopleList=[Ana, Ron,Jack, Tom, Lisa, Frank];

class myPerson {
  String name;
  int age;
  int height;
  myPerson({required this.name, required this.age, required this.height});
}

List<myPerson> mypeople = [];

Future<List<myPerson>> getPeople() async {

for(var p in await PeopleList()) {
      if(p.isNotEmpty){  
         mypeople.add(MyPerson(name: p.name,age:p.age , height:p.height);
   }
  }  
 return mypeople;  
}

2

Answers


  1. When you print an object, Flutter calls the toString() method on that object. And since you don’t implement toString in your myPerson class, you end up with the default Object.toString() implementation, which indeed shows instanceOf <whatEverClassTheObjectIsOf>.

    If you want it to print something different, override toString() in your myPerson class.

    Also see, this Dart tutorial on overriding methods, which uses toString in its example.

    Login or Signup to reply.
  2. If you want to print out the values of the properties in your class (myPerson), you will have to specify them in your print method.
    For example:

    for (var person in mypeople) {
      print('Name: ${person.name}, Age: ${person.age}, Height: ${person.height}');
    }
    

    Or you can override the toString method in your class (myPerson) to print out the values of the properties.

    class myPerson {
      String name;
      int age;
      int height;
      myPerson({required this.name, required this.age, required this.height});
    
      @override
      String toString() {
        return 'Name: $name, Age: $age, Height: $height';
      }
    }
    

    Then you can print the list of people like this:

    for (var person in mypeople) {
      print(person);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search