Pamela
Pamela

Reputation: 475

How to null-check a simple Function in Dart?

void main() {
  Car myCar = Car(drive: slowDrive);
  myCar.drive();
}

class Car {
  Car({this.drive});
  Function? drive;
}

void slowDrive() {
  print('Driving slowly');
}

void fastDrive() {
  print('Driving fast');
}

The error says An expression whose value can be null must be null-checked before it can be dereferenced.

How can I null-check this?

Upvotes: 2

Views: 1277

Answers (2)

Peter Haddad
Peter Haddad

Reputation: 80914

You can make the parameter drive required:

void main() {
  Car myCar = Car(drive : slowDrive);
  myCar.drive();
}

class Car {
  Car({required this.drive});
  Function drive;
}

void slowDrive() {
  print('Driving slowly');
}

void fastDrive() {
  print('Driving fast');
}

To guarantee that you never see a null parameter with a non-nullable type, the type checker requires all optional parameters to either have a nullable type or a default value. What if you want to have a named parameter with a nullable type and no default value? That would imply that you want to require the caller to always pass it. In other words, you want a parameter that is named but not optional.

https://dart.dev/null-safety/understanding-null-safety#required-named-parameters

Upvotes: 0

ikerfah
ikerfah

Reputation: 2862

It can be done using .call()

void main() {
  Car myCar = Car(drive: slowDrive);
  myCar.drive?.call();
}

class Car {
  Car({this.drive});
  Function? drive;
}

void slowDrive() {
  print('Driving slowly');
}

void fastDrive() {
  print('Driving fast');
}

call accepts also function with parameters

void main() {
  Car myCar = Car(drive: slowDrive);
  myCar.drive?.call(5);
}

class Car {
  Car({this.drive});
  Function(int)? drive;
}

void slowDrive(int a) {
  print('Driving slowly');
}

void fastDrive(int a) {
  print('Driving fast');
}

Upvotes: 6

Related Questions