Longrunning operations with background thread in the Flutter

Reading time: < 1 minute

Sometimes we need to perform some longrunning tasks in the background thread, while UI thread should continue working without any freezes. Here and here you can see examples of waiting for network calls while UI “spinning”.

But have can we do the same for some 1000 items in 100 lists matching for example? In this case, we can use compute method. It’s part of ‘package: flutter/foundation.dart’, to use compute we need to pass top-level function and it’s parameters if needed. Add async to wait for function end, Like this:

async compute(topFunction, param);

Here you have full example code:

import 'dart:io';

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

class BackgroundCalculationExample extends StatefulWidget {
  @override
  _BackgroundCalculationExampleState createState() => _BackgroundCalculationExampleState();
}

class _BackgroundCalculationExampleState extends State<BackgroundCalculationExample> {
  bool load = true;
  String title;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: buildCenter(),
      ),
    );
  }

  Widget buildCenter() {
    if (load)
      return Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          CircularProgressIndicator(),
          MaterialButton(
              color: Colors.orangeAccent,
              onPressed: () async {
                String result = await compute(longRunningOperation, const Duration(seconds: 2));
                setState(() {
                  load = false;
                  title = result;
                });
              },
              child: Text("RUN"))
        ],
      );
    else
      return Text(title);
  }
}

String longRunningOperation(Duration duration) {
  sleep(duration);
  return "LOADED";
}

As we can see below, spinner keeps running while we wait for end of longRunningOperation.

Leave a Reply

Your email address will not be published. Required fields are marked *