0

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
1
  • 1
    I think you need to create a new list... so something like List<Hobbies> hobbies = new List<Hobbies>(); Right now I guess it's declared but not initialized. (has a type, but is null) Commented Jul 29, 2020 at 19:41

2 Answers 2

2

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());
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.