Reputation: 12566
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;
});
}
Upvotes: 25
Views: 39164
Reputation: 511846
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;
}
compute
must be a top level function (not inside a class).Here is the full code in context. The circular progress indicator stops spinning because the UI is blocked when you do the computationallyExpensiveTask
directly.
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(),
ElevatedButton(
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;
}
Upvotes: 15
Reputation: 1559
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
Upvotes: 28