Mostafa Pakizeh
Mostafa Pakizeh

Reputation: 3

print something and result is null

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

Upvotes: 0

Views: 48

Answers (2)

Gwhyyy
Gwhyyy

Reputation: 9166

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

Upvotes: 2

Ivone Djaja
Ivone Djaja

Reputation: 753

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

Upvotes: 2

Related Questions