Home > Blockchain >  Why use a Microtask in Flutter?
Why use a Microtask in Flutter?

Time:12-22

I'm learning Flutter and recently found Microtasks. I've read up on it and I understand what Microtasks are and what the Microtask queue is, but am still a little confused why I'd ever use one.

I'd appreciate an real-world example or explanation of when/why to use a Microtask.

Thanks.

CodePudding user response:

Here is a concrete example I found usefull to understand it. Some operation while the widget tree is building are forbidden. Most of the time it is used in initState

Consider you are using the provider package

initState() {
  super.initState();
  context.read<MyNotifier>().fetchSomething(); // -> not work
}

Actually fetchSomething() will call a http package to get data and some stuff. This is not allowed because the state update is synchronous and here there is a lap of time during the value (new/old) can change (here before and after the data loaded from http).

This could cause inconsistencies in your UI and is therefore not allowed.

A workaround is to use a microtask to achieve it. This will schedule it to happen on the next async task cycle (i.e. after build is complete here).

initState() {
  super.initState();
  Future.microtask(() =>
    context.read<MyNotifier>().fetchSomething(someValue); --> this work
  );
}

To sum up this example, Microtask is usually created if we need to complete a task later, but before returning control to the event loop.

  • Related