Flutter- compute method

Here is an example of compute:

final sum = await compute(computationallyExpensiveTask, 1000000000);

And this is the function that is run in the compute isolate:

int computationallyExpensiveTask(int value) {
  var sum = 0;
  for (var i = 0; i <= value; i++) {
    sum += i;
  }
  print('finished');
  return sum;
}

Notes:

  • As mentioned in the accepted answer, the function that you give to compute must be a top level function (not inside a class).

Code

Here is the full code in context. The circular progress indicator stops spinning because the UI is blocked when you do the computationallyExpensiveTask directly.

enter image description here

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          CircularProgressIndicator(),
          RaisedButton(
            child: Text('start'),
            onPressed: () async {
              final sum = computationallyExpensiveTask(1000000000);
              //final sum = await compute(computationallyExpensiveTask, 1000000000);
              print(sum);
            },
          )
        ],
      ),
    );
  }
}


int computationallyExpensiveTask(int value) {
  var sum = 0;
  for (var i = 0; i <= value; i++) {
    sum += i;
  }
  print('finished');
  return sum;
}

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

Tags:

Dart

Flutter