Home > Mobile >  print something and result is null
print something and result is null

Time:11-12

here is the code and when I run code it's print my result correctly but there is a null as result (in line 4) :

  main() {
      var ferrari = Car();
      ferrari.armor = 85;
      print(ferrari.armor);
  }
  class Car {
      int? _armor;

  int? get armor {
      return _armor;
  }
  set armor(int? armor) {
      if (armor != null && armor < 100) {
      print(true);
   }  else {
      print(false);
   }
 }

CodePudding user response:

In the set function, you need to set the _armor.

set armor(int? armor) {
  if (armor != null && armor < 100) {
    _armor = armor; // Set _armor to armor here.
    print(true);
  } else {
    print(false);
  }
}

CodePudding user response:

you have a variable that you give to it a custom getter and setter, so basically when you call the getter ferrari.armor it returns the _armor from your class, but since you see the _armor in your code will be always null because actaully you didn't give it any value in the setter, so it stays always null. here propably what you wanted to do.

    main() {
  var ferrari = Car();
  ferrari.armor = 85;
  print(ferrari.armor);
}

class Car {
  int? _armor;

  int? get armor {
    return _armor;
  }

  set armor(int? armor) {

    if (armor != null && armor < 100) {
    _armor = armor; // add this

      print(true);
    } else {
      print(false);
    }
  }
}
  • Related