0

This code is in error:


void functionA (){
  int varA;
  functionB();
}

void functionB(){
  varA = 2; ///???
}

This code is an error because, obviously, inside of functionB, "varA" has not been defined and I am referencing an undeclared variable.

My question is, given the scoping/hierarchy of these two functions, is there a way to change functionA's varA via code inside of functionB (and then calling functionB inside of functionA)?

I know you can do something similar with classes by passing the current class instance as a parameter into a function with the "this" keyword. This way, you can change local class variables via a function even if the function is globally defined. Can something similar be done with nested functions? Thanks!

William Egert
  • 47
  • 1
  • 6

1 Answers1

0

You can pass a function as an argument in dart like this:

void functionA () {
  int varA = 0;
  
  print(varA);
  
  functionB((i) {
    varA = i;
  });
  
  print(varA);
}

/// The parameter is a function that has no return type and takes an integer parameter.
void functionB(void Function(int) setVarA){
  setVarA(100);
}

It outputs:

0
100

You can change the variable like this or you can just make functionB's return type as int and assign its return value to varA. Depends on what you are trying to achieve.

Afridi Kayal
  • 2,112
  • 1
  • 5
  • 15
  • Thank you for your answer, I'm going to punch this into my IDE right now and see if I can wrap my brain around it! – William Egert Dec 26 '20 at 06:33
  • Thank you, while a bit complicated and indirect, this does indeed work. This also leads me a deeper understanding of dart - the ability to pass functions as arguments into functions. I'm sure I will find more uses to this device as I continue my learning journey. Thank you! – William Egert Dec 26 '20 at 16:41