flutter-handling-concurrency by flutter/skills
npx skills add https://github.com/flutter/skills --skill flutter-handling-concurrencyDart 采用由事件循环驱动的单线程执行模型(类似于 iOS 主循环)。默认情况下,所有 Flutter 应用程序代码都在主隔离区上运行。
async/await): 用于非阻塞的 I/O 任务(网络请求、文件访问)。在等待 Future 完成时,事件循环会继续处理其他事件。应用以下条件逻辑来确定正确的并发方法:
async/。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
awaitasync/await。Isolate.run()。Isolate.spawn() 配合 ReceivePort 和 SendPort。使用此工作流程来获取和显示非阻塞的异步数据。
任务进度:
async 关键字标记数据获取函数。Future<T>。await 关键字让出执行权,直到操作完成。FutureBuilder<T> 中(对于流则使用 StreamBuilder)。ConnectionState.waiting、hasError 和 hasData 状态。使用此工作流程处理一次性的、CPU 密集型任务(使用 Dart 2.19+)。
任务进度:
Isolate.run() 并传递回调函数。await Isolate.run() 的结果。使用此工作流程处理需要持续双向通信的持久后台进程。
任务进度:
ReceivePort 以监听消息。Isolate.spawn() 派生工作隔离区,并将 ReceivePort.sendPort 作为初始消息传递。ReceivePort。SendPort 发送回主隔离区。SendPort,以便将来发送消息。ReceivePort 实例上实现监听器以处理传入消息。// 1. 定义异步操作
Future<String> fetchUserData() async {
await Future.delayed(const Duration(seconds: 2)); // 模拟网络 I/O
return "User Data Loaded";
}
// 2. 在 UI 中使用
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchUserData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Result: ${snapshot.data}');
}
},
);
}
Isolate.run)import 'dart:isolate';
import 'dart:convert';
// 1. 定义繁重计算回调
// 注意:遵循严格的单参数签名要求。
List<dynamic> decodeHeavyJson(String jsonString) {
return jsonDecode(jsonString) as List<dynamic>;
}
// 2. 卸载到工作隔离区
Future<List<dynamic>> processDataInBackground(String rawJson) async {
// Isolate.run 派生隔离区,运行计算,返回值,然后退出。
final result = await Isolate.run(() => decodeHeavyJson(rawJson));
return result;
}
ReceivePort / SendPort)import 'dart:isolate';
class WorkerManager {
late SendPort _workerSendPort;
final ReceivePort _mainReceivePort = ReceivePort();
Isolate? _isolate;
Future<void> initialize() async {
// 1. 派生隔离区并传递主隔离区的 SendPort
_isolate = await Isolate.spawn(_workerEntry, _mainReceivePort.sendPort);
// 2. 监听来自工作隔离区的消息
_mainReceivePort.listen((message) {
if (message is SendPort) {
// 第一条消息是工作隔离区的 SendPort
_workerSendPort = message;
_startCommunication();
} else {
// 后续消息是数据负载
print('Main Isolate received: $message');
}
});
}
void _startCommunication() {
// 向工作隔离区发送数据
_workerSendPort.send("Process this data");
}
// 3. 工作隔离区入口点
static void _workerEntry(SendPort mainSendPort) {
final workerReceivePort = ReceivePort();
// 将工作隔离区的 SendPort 发送回主隔离区
mainSendPort.send(workerReceivePort.sendPort);
// 监听传入的任务
workerReceivePort.listen((message) {
print('Worker Isolate received: $message');
// 执行工作并发送结果回去
final result = "Processed: $message";
mainSendPort.send(result);
});
}
void dispose() {
_mainReceivePort.close();
_isolate?.kill();
}
}
每周安装量
1.8K
代码仓库
GitHub 星标数
792
首次出现
11 天前
安全审计
已安装于
codex1.7K
gemini-cli1.7K
opencode1.7K
github-copilot1.7K
kimi-cli1.7K
cursor1.7K
Dart utilizes a single-threaded execution model driven by an Event Loop (comparable to the iOS main loop). By default, all Flutter application code runs on the Main Isolate.
async/await): Use for non-blocking I/O tasks (network requests, file access). The Event Loop continues processing other events while waiting for the Future to complete.Apply the following conditional logic to determine the correct concurrency approach:
async/await on the Main Isolate.async/await on the Main Isolate.Isolate.run().Isolate.spawn() with ReceivePort and SendPort.Use this workflow to fetch and display non-blocking asynchronous data.
Task Progress:
async keyword.Future<T> from the function.await keyword to yield execution until the operation completes.FutureBuilder<T> (or StreamBuilder for streams).ConnectionState.waiting, hasError, and hasData states within the builder.Use this workflow for one-off, CPU-intensive tasks using Dart 2.19+.
Task Progress:
Isolate.run() passing the callback.await the result of Isolate.run() in the Main Isolate.Use this workflow for persistent background processes requiring continuous bidirectional communication.
Task Progress:
ReceivePort on the Main Isolate to listen for messages.Isolate.spawn(), passing the ReceivePort.sendPort as the initial message.ReceivePort.SendPort back to the Main Isolate via the initial port.SendPort in the Main Isolate for future message dispatching.ReceivePort instances to handle incoming messages.// 1. Define the async operation
Future<String> fetchUserData() async {
await Future.delayed(const Duration(seconds: 2)); // Simulate network I/O
return "User Data Loaded";
}
// 2. Consume in the UI
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchUserData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Result: ${snapshot.data}');
}
},
);
}
Isolate.run)import 'dart:isolate';
import 'dart:convert';
// 1. Define the heavy computation callback
// Note: Adhering to the strict single-argument signature requirement.
List<dynamic> decodeHeavyJson(String jsonString) {
return jsonDecode(jsonString) as List<dynamic>;
}
// 2. Offload to a worker isolate
Future<List<dynamic>> processDataInBackground(String rawJson) async {
// Isolate.run spawns the isolate, runs the computation, returns the value, and exits.
final result = await Isolate.run(() => decodeHeavyJson(rawJson));
return result;
}
ReceivePort / SendPort)import 'dart:isolate';
class WorkerManager {
late SendPort _workerSendPort;
final ReceivePort _mainReceivePort = ReceivePort();
Isolate? _isolate;
Future<void> initialize() async {
// 1. Spawn isolate and pass the Main Isolate's SendPort
_isolate = await Isolate.spawn(_workerEntry, _mainReceivePort.sendPort);
// 2. Listen for messages from the Worker Isolate
_mainReceivePort.listen((message) {
if (message is SendPort) {
// First message is the Worker's SendPort
_workerSendPort = message;
_startCommunication();
} else {
// Subsequent messages are data payloads
print('Main Isolate received: $message');
}
});
}
void _startCommunication() {
// Send data to the worker
_workerSendPort.send("Process this data");
}
// 3. Worker Isolate Entry Point
static void _workerEntry(SendPort mainSendPort) {
final workerReceivePort = ReceivePort();
// Send the Worker's SendPort back to the Main Isolate
mainSendPort.send(workerReceivePort.sendPort);
// Listen for incoming tasks
workerReceivePort.listen((message) {
print('Worker Isolate received: $message');
// Perform work and send result back
final result = "Processed: $message";
mainSendPort.send(result);
});
}
void dispose() {
_mainReceivePort.close();
_isolate?.kill();
}
}
Weekly Installs
1.8K
Repository
GitHub Stars
792
First Seen
11 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex1.7K
gemini-cli1.7K
opencode1.7K
github-copilot1.7K
kimi-cli1.7K
cursor1.7K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装