Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter- compute method

Tags:

flutter

dart

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;
    });
  }
like image 916
Daibaku Avatar asked Sep 06 '18 04:09

Daibaku


People also ask

How does compute work in flutter?

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).

What is the purpose of compute () function in DART?

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.

How do you isolate in flutter?

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.

What is isolate Dart?

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.


1 Answers

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

like image 74
Vilsad P P Avatar answered Dec 07 '22 16:12

Vilsad P P