Loading...
Loading...
Execute long-running tasks in a background thread in Flutter
npx skill4agent add flutter/skills flutter-concurrencydart:convertdart:isolatedart:convertjson_serializablebuild_runnerasyncawaitIsolate.run()ReceivePortSendPortcompute()dart:isolatejson_serializableimport 'dart:convert';
class User {
final String name;
final String email;
User(this.name, this.email);
User.fromJson(Map<String, dynamic> json)
: name = json['name'] as String,
email = json['email'] as String;
Map<String, dynamic> toJson() => {'name': name, 'email': email};
}json_serializablejson_annotationdependenciesbuild_runnerjson_serializabledev_dependenciesimport 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
(explicitToJson: true)
class User {
final String name;
(name: 'email_address', defaultValue: 'unknown@example.com')
final String email;
User(this.name, this.email);
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}dart run build_runner build --delete-conflicting-outputs*.g.dartIsolate.run()import 'dart:convert';
import 'dart:isolate';
import 'package:flutter/services.dart';
Future<List<User>> fetchAndParseUsers() async {
// 1. Load data on the main isolate
final String jsonString = await rootBundle.loadString('assets/large_users.json');
// 2. Spawn an isolate, pass the computation, and await the result
final List<User> users = await Isolate.run<List<User>>(() {
// This runs on the background isolate
final List<dynamic> decoded = jsonDecode(jsonString) as List<dynamic>;
return decoded.cast<Map<String, dynamic>>().map(User.fromJson).toList();
});
return users;
}ReceivePortSendPortimport 'dart:isolate';
Future<void> setupLongLivedIsolate() async {
final ReceivePort mainReceivePort = ReceivePort();
await Isolate.spawn(_backgroundWorker, mainReceivePort.sendPort);
final SendPort backgroundSendPort = await mainReceivePort.first as SendPort;
// Send data to the background isolate
final ReceivePort responsePort = ReceivePort();
backgroundSendPort.send(['https://api.example.com/data', responsePort.sendPort]);
final result = await responsePort.first;
print('Received from background: $result');
}
static void _backgroundWorker(SendPort mainSendPort) async {
final ReceivePort workerReceivePort = ReceivePort();
mainSendPort.send(workerReceivePort.sendPort);
await for (final message in workerReceivePort) {
final String url = message[0] as String;
final SendPort replyPort = message[1] as SendPort;
// Perform heavy work here
final parsedData = await _heavyNetworkAndParse(url);
replyPort.send(parsedData);
}
}FutureBuilderimport 'package:flutter/material.dart';
class UserListScreen extends StatefulWidget {
const UserListScreen({super.key});
State<UserListScreen> createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
late Future<List<User>> _usersFuture;
void initState() {
super.initState();
_usersFuture = fetchAndParseUsers(); // Calls the Isolate.run method
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Users')),
body: FutureBuilder<List<User>>(
future: _usersFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('No users found.'));
}
final users = snapshot.data!;
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(users[index].name),
subtitle: Text(users[index].email),
);
},
);
},
),
);
}
}dart:uirootBundledart:isolatecompute()package:flutter/foundation.dartIsolate.run()compute()SendPortWidgetStatefulWidgetsetStatedart:mirrors