vintage / scratcher

Scratch card widget which temporarily hides content from user.
https://pub.dev/packages/scratcher
MIT License
572 stars 67 forks source link

Answer to null check question in painter's code #55

Closed feinstein closed 1 month ago

feinstein commented 8 months ago

The painter's code have this question:

  if (image != null && imageFit != null) {
    // TODO: why the ! are needed here, as check against null been performed?

The answer is, the compiler can't know if a class' filed is always null or not, because this field could be a getter that returns null sometimes and returns a value other times. You need to use the ! operator or you can copy that field to a local variable and check that variable, then the compiler knows it's not null at all.

Example:

  final image = this.image;
  if (image != null && imageFit != null) {
    // compiler knows image is not null and you don't need to use the ! operator.
vintage commented 8 months ago

Thanks! Labeling it as good first issue. If you or anyone else want to make the PR to resolve that, I'm happy to merge!

feinstein commented 8 months ago

No need to fix, it's just a preference of style. Copying to a local variable is safer, but just for extreme cases.