DEV Community

oganao
oganao

Posted on

[Not solved]Difference among value, sync, microtask and async on Future

I am still learning Dart. Now I am focusing on Future this week. I made toy codes to understand Future. Syntax of Future is fine for me, but I still don't comprehend Future in detail.

For example, following snippets seem to be the same, but they are not.

Future.value and Future.sync destruct a local value, but Future.microtask and async function do not.

I guess a reddit article could give me a clue. But it seems to me this is not the case for me.

void main() async{
  print('--work01--');
  await work01();
  print('--work02--');
  await work02();
  print('--work03--');
  await work03();
  print('--work04--');
  await work04();
}

work01() async {
  int c = 2;
  Future<int> x = Future.value(++c); // 3->3
  print(c);
  print(await x);
}

work02() async {
  int c = 2;
  Future<int> x = Future.sync(()=>++c); // 3->3
  print(c);
  print(await x);
}

work03() async {
  int c = 2;
  Future<int> x = Future.microtask(()=>++c); // 2->3
  print(c);
  print(await x);
}

work04() async {
  Future<int> foo(int x) async {
    return ++x;
  }
  int c = 2;
  Future<int> x = foo(c); // 2->3
  print(c);
  print(await x);
}
Enter fullscreen mode Exit fullscreen mode

Console

--work01--
3
3
--work02--
3
3
--work03--
2
3
--work04--
2
3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)