Home > Mobile >  I intend to define and use a setter normally in Dart, but I get an error : The method 'setAnima
I intend to define and use a setter normally in Dart, but I get an error : The method 'setAnima

Time:06-13

void main(){

  Animal a1 = Animal();
  Cat c1 = Cat();

  AnimalCage ac1 = AnimalCage();

  ac1.setAnimal(a1); //error: The method 'setAnimal' isn't defined for the type 'AnimalCage'.


}

class AnimalCage{
  Animal? _animal;

  set setAnimal(Animal animal){
    print('animals setter');
    _animal = animal;
  }
}

class Animal {

}

I get the above error, but I don't know what's wrong.

Is there something wrong with using the setter?

If I define setAnimal as a method, the error will disappear, but I think there is no problem with the setter.

CodePudding user response:

Since setAnimal is a setter, you don't use it like a method.

Simply do:

ac1.setAnimal = a1;

To avoid confusion, you shouldn't prefix your setter names with set, just use the name of whatever you want to set like so:

set animal(Animal animal){
    print('animals setter');
    _animal = animal;
  }

Then use the setter like so:

ac1.animal = a1;

If you really want to use the method syntax, then create a method instead, like so:

void setAnimal(Animal animal){
    print('animals setter');
    _animal = animal;
  }

Then you can use it:

ac1.setAnimal(a1); 
  •  Tags:  
  • dart
  • Related