I'm trying to execute heavy method by compute()
.
I tried like so.
After loop
executed, Text
widget update but result
returns 0 almost right after button was pressed.
Does anyone know what am I missing?
int _counter;
static int loop(int val) {
int count = 0;
for (int i = 1; i <= val; i++) {
count += i;
}
return count;
}
Future<void> _onPressed() async {
int result = await compute(loop, 1000000000000000000);
setState(() {
_counter = result;
});
}
Compute function takes two parameters : A future or a function but that must be static (as in dart threads does not share memory so they are class level members not object level). Argument to pass into the function, To send multiple arguments you can pass it as a map(as it only supports single argument).
Dart is a single threaded language, but it comes with a handy compute function to spawn isolates. In a nutshell, the compute function is useful for doing extra work on a different "thread"--it's actually an isolate--so your flutter app does not experience "jank". Jank occurs when the UI doesn't render smoothly.
The first way to create an isolate is by using the Isolate. spawn() call. We pass in the method we want to run as the first parameter, while the second argument is the parameter we want to pass to the isolate.
Using isolates, your Dart code can perform multiple independent tasks at once, using additional processor cores if they're available. Isolates are like threads or processes, but each isolate has its own memory and a single thread running an event loop.
According to https://api.flutter.dev/flutter/foundation/compute-constant.html,
The callback argument must be a top-level function, not a closure or an instance or static method of a class.
Please remove the static
keyword, it should work fine
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With