Home > Net >  Dart: How to pass function as parameter
Dart: How to pass function as parameter

Time:01-17

Id like to call a function from another function, this is my code:

  void fooA () {
    //do something
  }
  
  void fooB (fooC) {
    fooC();
  }
  
  fooB (fooA);

Why is fooA not executed?

CodePudding user response:

The code you provided functions:

void fooA () {
  print('hi');
}

void fooB (fooC) {
  fooC();
}

main() {
  fooB (fooA);
}

Output:

hi

However, it is better to fully type function arguments, as in:

void fooA() {
  print('hi');
}

void fooB(void Function() fooC) {
  fooC();
}

main() {
  fooB(fooA);
}

Note the fully descriptive type declaration void Function() fooC. Doing so enables the compiler to use static type checking to ensure the passed in function has the correct parameter and return types.

References

CodePudding user response:

You need to change your fooB to this:

void fooB (Function fooC) {
  fooC();
}
  • Related