text
stringlengths 1
474
|
---|
Refer to the next section for more information on doing work
|
in the background, and how Flutter differs from iOS.<topic_end>
|
<topic_start>
|
Moving to the background thread
|
Since Flutter is single threaded and runs an event loop
|
(like Node.js), you don’t have to worry about
|
thread management or spawning background threads.
|
If you’re doing I/O-bound work,
|
such as disk access or a network call,
|
then you can safely use async/await and you’re done.
|
If, on the other hand, you need to do computationally intensive
|
work that keeps the CPU busy, you want to move it to an
|
Isolate to avoid blocking the event loop.For I/O-bound work, declare the function as an async function,
|
and await on long-running tasks inside the function:
|
<code_start>Future<void> loadData() async {
|
final Uri dataURL = Uri.parse('https://jsonplaceholder.typicode.com/posts');
|
final http.Response response = await http.get(dataURL);
|
setState(() {
|
data = jsonDecode(response.body);
|
});
|
}<code_end>
|
This is how you typically do network or database calls,
|
which are both I/O operations.However, there are times when you might be processing
|
a large amount of data and your UI hangs.
|
In Flutter, use Isolates to take advantage of
|
multiple CPU cores to do long-running or
|
computationally intensive tasks.Isolates are separate execution threads that do not share
|
any memory with the main execution memory heap.
|
This means you can’t access variables from the main thread,
|
or update your UI by calling setState().
|
Isolates are true to their name, and cannot share memory
|
(in the form of static fields, for example).The following example shows, in a simple isolate,
|
how to share data back to the main thread to update the UI.
|
<code_start>Future<void> loadData() async {
|
final ReceivePort receivePort = ReceivePort();
|
await Isolate.spawn(dataLoader, receivePort.sendPort);
|
// The 'echo' isolate sends its SendPort as the first message.
|
final SendPort sendPort = await receivePort.first as SendPort;
|
final List<Map<String, dynamic>> msg = await sendReceive(
|
sendPort,
|
'https://jsonplaceholder.typicode.com/posts',
|
);
|
setState(() {
|
data = msg;
|
});
|
}
|
// The entry point for the isolate.
|
static Future<void> dataLoader(SendPort sendPort) async {
|
// Open the ReceivePort for incoming messages.
|
final ReceivePort port = ReceivePort();
|
// Notify any other isolates what port this isolate listens to.
|
sendPort.send(port.sendPort);
|
await for (final dynamic msg in port) {
|
final String url = msg[0] as String;
|
final SendPort replyTo = msg[1] as SendPort;
|
final Uri dataURL = Uri.parse(url);
|
final http.Response response = await http.get(dataURL);
|
// Lots of JSON to parse
|
replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>);
|
}
|
}
|
Future<List<Map<String, dynamic>>> sendReceive(SendPort port, String msg) {
|
final ReceivePort response = ReceivePort();
|
port.send(<dynamic>[msg, response.sendPort]);
|
return response.first as Future<List<Map<String, dynamic>>>;
|
}<code_end>
|
Here, dataLoader() is the Isolate that runs in
|
its own separate execution thread.
|
In the isolate, you can perform more CPU intensive
|
processing (parsing a big JSON, for example),
|
or perform computationally intensive math,
|
such as encryption or signal processing.You can run the full example below:
|
<code_start>import 'dart:async';
|
import 'dart:convert';
|
import 'dart:isolate';
|
import 'package:flutter/material.dart';
|
import 'package:http/http.dart' as http;
|
void main() {
|
runApp(const SampleApp());
|
}
|
class SampleApp extends StatelessWidget {
|
const SampleApp({super.key});
|
@override
|
Widget build(BuildContext context) {
|
return const MaterialApp(
|
title: 'Sample App',
|
home: SampleAppPage(),
|
);
|
}
|
}
|
class SampleAppPage extends StatefulWidget {
|
const SampleAppPage({super.key});
|
@override
|
State<SampleAppPage> createState() => _SampleAppPageState();
|
}
|
class _SampleAppPageState extends State<SampleAppPage> {
|
List<Map<String, dynamic>> data = <Map<String, dynamic>>[];
|
@override
|
void initState() {
|
super.initState();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.