Home > Software engineering >  Future.delayed execution
Future.delayed execution

Time:11-16

Got some example.

void main() {
  A a = A();
  transform(a);
  print(a.str   ' sync');
}

Future<void> transform(A a) async {
  await Future.delayed(Duration(seconds: 3), () => a.str = 'B');
  print(a.str   ' async');
}

class A {
  String str = 'A';
}

And output:

A sync
B async

And next example

void main() {
  A a = A();
  transform(a);
  print(a.str   ' sync');
}

Future<void> transform(A a) async {
  Function f = () {
    a.str = 'B';
  };
  await Future.delayed(Duration(seconds: 3), f());
  print(a.str   ' async');
}

class A {
  String str = 'A';
}

With output:

B sync
B async

Am i right thinking that f() is executed but just not returned in the second case, so i've got the a.str value modified imidiatly and returned later? Or what the right answer?

CodePudding user response:

In the second example you have the following line:

await Future.delayed(Duration(seconds: 3), f());

What you are doing here is executing the function pointed at by the variable f and uses the result from this method as the second argument to Future.delaye. The reason for this is that you have () right after the name of the variable f, which is used to indicate you want to execute the method pointed at by f without any arguments.

What you should have done instead (if you want to send the function itself as the second argument for Future.delayed) is just use f:

await Future.delayed(Duration(seconds: 3), f);

CodePudding user response:

await Future.delayed(Duration(seconds: 3),(){f();});

here what i wanted

  •  Tags:  
  • dart
  • Related