SlugSeason
SlugSeason

Reputation: 15

Adding List<object> to class

New programmer here, I'm trying to add a List object to a list within another class but it keeps giving me an error.I've been stuck on this problem for hours now

void main() 
{
  List<Hobbies> hobby;
  Hobbies hobbies = new Hobbies("Football");
  hobby.add(hobbies);
  User user1 = new User("Harris", 22, hobby);
  print(user1.getAge());
  
}

class User 
{
  String name;
  int age;
  List<Hobbies> hobbies;
  
  User(String name, int age, List<Hobbies> hobbies) 
  {
    this.name = name;
    this.age = age;
    this.hobbies = hobbies;
  }
  
  getAge() 
  {
    print(name);
  }
}

class Hobbies 
{
  String name;
  
  Hobbies(String name) 
  {
    this.name = name;
  }
  
  getAge() 
  {
    print(name);
  }
}

The error i keep getting

TypeError: C.JSNull_methods.add$1 is not a functionError: TypeError: C.JSNull_methods.add$1 is not a function

Upvotes: 0

Views: 129

Answers (2)

scrimau
scrimau

Reputation: 1385

You need to initialize a List, otherwise it is null and null has no add, so do this:

final hobby = List<Hobbies>(); 
// or final List<Hobbies> hobby = [];
// or final hobby = <Hobby>[];
Hobbies hobbies = new Hobbies("Football");
hobby.add(hobbies);
final user1 = User("Harris", 22, hobby);

Upvotes: 0

Aleksandar
Aleksandar

Reputation: 1588

You mixed a lot of things here, but let's try to unwrap it all one by one. :) So few things regarding naming conventions to make your life easier:

  1. Don't use plurals for object names if they are representing one item, and not a list of something.
  2. Always use plurals for property of type list.
  3. Getter methods should always return a type, if you miss that part, you won't see compile time errors your upper project has at the moment trying to print variables instead of returning values, and than again printing in main file for 2nd time...

If you follow those principles, you would get your objects looking like this

class User {
  String name;
  int age;
  List<Hobby> hobbies;

  User(String name, int age, List<Hobby> hobbies) {
    this.name = name;
    this.age = age;
    this.hobbies = hobbies;
  }

  int getAge() => print(name);
}

class Hobby {
  String name;

  Hobby(String name) {
    this.name = name;
  }

  String getName() => this.name;
}

After this is sorted, let's approach adding data and initialising those objects:

void main() {
  List<Hobby> hobbies = [Hobby("Football")];
  User user1 = new User("Harris", 22, hobbies);
  print(user1.getAge().toString());
}

Upvotes: 2

Related Questions