Flutter BLoC + Isolate: Enhancing Performance with Background Processing

Mohammed shamseer pv
3 min readAug 27, 2024

--

Introduction

In this post, I’ll guide you through how to use Flutter BLoC with isolates to handle background processing efficiently. When working on complex apps, we often encounter heavy operations that can slow down the UI if run on the main thread. Using isolates allows us to perform these tasks in the background, ensuring our app remains responsive.

Why Use Isolates?

Isolates in Dart allow you to run tasks in a separate memory space, effectively enabling multithreading. This is crucial for long-running tasks like network calls, file processing, or heavy computations that could otherwise freeze the UI.

Getting Started

Step 1: Setting Up Your Flutter Project

Ensure you have the necessary dependencies in your pubspec.yaml:

dependencies:
flutter:
sdk: flutter
flutter_bloc: ^8.0.0

Step 2: Creating the BLoC

Let’s create a BLoC that will manage the state of our app. This BLoC will trigger an isolate to perform background processing.

import 'dart:ffi';
import 'dart:isolate';

import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:injectable/injectable.dart';

part 'news_event.dart';
part 'news_state.dart';
part 'news_bloc.freezed.dart';

@injectable
class NewsBloc extends Bloc<NewsEvent, NewsState> {
NewsBloc() : super(NewsState.initial()) {
on<_GetNews>((event, emit) async {
// Show a loading state or progress indicator here if needed
emit(state.copyWith(myData: "Loading..."));

// Running the heavy computation in a separate isolate
final result = await _computeInIsolate(int.parse(event.data));

// Emit the result from the isolate
emit(state.copyWith(myData: result.toString()));
});
}

static int heavyComputation(int data) {
var total = 0;
for (var i = 0; i < data; i++) {
total += i;
}
return total;
}

Future<int> _computeInIsolate(int data) async {
// Create a ReceivePort for the isolate to send data back
final receivePort = ReceivePort();

// Spawn the isolate
await Isolate.spawn(_isolateEntry, receivePort.sendPort);

// Send data to the isolate and wait for the result
final sendPort = await receivePort.first as SendPort;
final response = ReceivePort();
sendPort.send([data, response.sendPort]);

return await response.first as int;
}

static void _isolateEntry(SendPort sendPort) async {
// Create a port to receive messages from the main isolate
final port = ReceivePort();
sendPort.send(port.sendPort);

// Handle incoming messages
await for (final message in port) {
final data = message[0] as int;
final replyTo = message[1] as SendPort;

// Perform the computation and send the result back
final result = heavyComputation(data);
replyTo.send(result);
}
}
}

Step 4: Building the UI

Now, let’s build a simple UI to trigger the computation.

import 'dart:isolate';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_bloc_full/application/news/news_bloc.dart';

class Home_page extends StatelessWidget {
const Home_page({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
children: [
BlocBuilder<NewsBloc, NewsState>(
builder: (context, state) {
return Text(state.myData);
},
),

LinearProgressIndicator(),
ElevatedButton(onPressed: (){

context.read<NewsBloc>().add(NewsEvent.getNews(data: "${Random().nextInt(1000000000)}"));
}, child: Text('data')),
],
)),
);
}
}

Step 5: Running the App

Run the app and click the button to compute the factorial in the background. The result should appear without freezing the UI.

Conclusion

By combining Flutter BLoC with isolates, you can achieve a responsive UI while handling intensive tasks in the background. This technique is crucial for creating a smooth user experience in complex Flutter applications.

Next Steps

Consider applying this technique to other time-consuming tasks in your apps, like processing large datasets or making multiple API calls.

--

--

Mohammed shamseer pv
Mohammed shamseer pv

Written by Mohammed shamseer pv

skilled in Flutter, Node.js, Python, and Arduino, passionate about AI and creating innovative solutions. Active in tech community projects.

Responses (1)