Reputation: 15
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
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
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:
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