简体   繁体   中英

Future.delayed execution

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?

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);
await Future.delayed(Duration(seconds: 3),(){f();});

这是我想要的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM