flutter-concurrency by flutter/skills
npx skills add https://github.com/flutter/skills --skill flutter-concurrency实现高级的 Flutter 数据处理,包括使用 Isolate 进行后台 JSON 序列化、异步状态管理以及平台感知的并发,以确保 UI 渲染流畅无卡顿,达到 60fps 以上。假设为标准 Flutter 环境(Dart 2.19+),可使用 dart:convert、dart:isolate 以及标准的状态管理模式。
在编写代码之前,使用以下决策树来确定正确的序列化和并发方法:
dart:convert)。
* 条件: JSON 模型是否复杂、嵌套,或是大型应用的一部分?json_serializable 和 build_runner)。async/ 在 上运行。
* 数据负载大(例如,> 1MB JSON)或计算量大?广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
awaitIsolate.run() 卸载到后台 Isolate。
* 条件: 后台任务是否需要持续的、双向的通信?ReceivePort 和 SendPort 实现一个长生命周期的 Isolate。
* 条件: 目标平台是 Web 吗?compute() 作为后备方案,因为标准 dart:isolate 线程在 Flutter Web 上不受支持。请先询问用户:
json_serializable)?"根据用户的偏好,实现数据模型。
选项 A:手动序列化
import '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};
}
选项 B:代码生成(json_serializable) 确保 json_annotation 在 dependencies 中,build_runner / json_serializable 在 dev_dependencies 中。
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable(explicitToJson: true)
class User {
final String name;
@JsonKey(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.dart 文件。
为防止 UI 卡顿,将繁重的 JSON 解析任务卸载到后台 isolate。
选项 A:短生命周期 Isolate(Dart 2.19+) 使用 Isolate.run() 处理一次性繁重计算。
import 'dart:convert';
import 'dart:isolate';
import 'package:flutter/services.dart';
Future<List<User>> fetchAndParseUsers() async {
// 1. 在主 isolate 上加载数据
final String jsonString = await rootBundle.loadString('assets/large_users.json');
// 2. 生成一个 isolate,传递计算任务,并等待结果
final List<User> users = await Isolate.run<List<User>>(() {
// 这部分在后台 isolate 上运行
final List<dynamic> decoded = jsonDecode(jsonString) as List<dynamic>;
return decoded.cast<Map<String, dynamic>>().map(User.fromJson).toList();
});
return users;
}
选项 B:长生命周期 Isolate(持续数据流) 使用 ReceivePort 和 SendPort 进行持续通信。
import 'dart:isolate';
Future<void> setupLongLivedIsolate() async {
final ReceivePort mainReceivePort = ReceivePort();
await Isolate.spawn(_backgroundWorker, mainReceivePort.sendPort);
final SendPort backgroundSendPort = await mainReceivePort.first as SendPort;
// 发送数据到后台 isolate
final ReceivePort responsePort = ReceivePort();
backgroundSendPort.send(['https://api.example.com/data', responsePort.sendPort]);
final result = await responsePort.first;
print('从后台收到: $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;
// 在此处执行繁重的工作
final parsedData = await _heavyNetworkAndParse(url);
replyPort.send(parsedData);
}
}
使用 FutureBuilder 将异步 isolate 计算绑定到 UI,确保主线程保持响应。
import 'package:flutter/material.dart';
class UserListScreen extends StatefulWidget {
const UserListScreen({super.key});
@override
State<UserListScreen> createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
late Future<List<User>> _usersFuture;
@override
void initState() {
super.initState();
_usersFuture = fetchAndParseUsers(); // 调用 Isolate.run 方法
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('用户列表')),
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('错误: ${snapshot.error}'));
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return const Center(child: Text('未找到用户。'));
}
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:ui、rootBundle 或操作 Flutter Widget。Isolate 不与主线程共享内存。dart:isolate 在 Flutter Web 上不受支持。如果目标是 Web,则必须使用 package:flutter/foundation.dart 中的 compute() 函数,而不是 Isolate.run(),因为 compute() 在 Web 平台上会安全地回退到主线程。SendPort 在 isolate 之间传递数据时,优先传递不可变对象(如字符串或不可修改的字节数据),以避免深拷贝的性能开销。Widget 属性视为不可变。当异步数据解析完成时,使用 StatefulWidget 和 setState(或状态管理包)来触发重建。dart:mirrors 进行 JSON 序列化。Flutter 禁用了运行时反射,以实现激进的摇树优化和 AOT 编译。始终使用手动解析或代码生成。每周安装量
980
代码仓库
GitHub 星标数
792
首次出现
2026年3月4日
安全审计
安装于
codex946
github-copilot943
cursor943
gemini-cli942
opencode942
kimi-cli941
Implements advanced Flutter data handling, including background JSON serialization using Isolates, asynchronous state management, and platform-aware concurrency to ensure jank-free 60fps+ UI rendering. Assumes a standard Flutter environment (Dart 2.19+) with access to dart:convert, dart:isolate, and standard state management paradigms.
Use the following decision tree to determine the correct serialization and concurrency approach before writing code:
dart:convert).json_serializable and build_runner).async/await.Isolate.run().ReceivePort and SendPort.compute() as a fallback, as standard threading is not supported on Flutter Web.STOP AND ASK THE USER:
json_serializable)?"Based on the user's preference, implement the data models.
Option A: Manual Serialization
import '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};
}
Option B: Code Generation (json_serializable) Ensure json_annotation is in dependencies, and build_runner / json_serializable are in dev_dependencies.
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable(explicitToJson: true)
class User {
final String name;
@JsonKey(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);
}
Validate-and-Fix: Instruct the user to run dart run build_runner build --delete-conflicting-outputs to generate the *.g.dart file.
To prevent UI jank, offload heavy JSON parsing to a background isolate.
Option A: Short-lived Isolate (Dart 2.19+) Use Isolate.run() for one-off heavy computations.
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;
}
Option B: Long-lived Isolate (Continuous Data Stream) Use ReceivePort and SendPort for continuous communication.
import '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);
}
}
Bind the asynchronous isolate computation to the UI using FutureBuilder to ensure the main thread remains responsive.
import 'package:flutter/material.dart';
class UserListScreen extends StatefulWidget {
const UserListScreen({super.key});
@override
State<UserListScreen> createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
late Future<List<User>> _usersFuture;
@override
void initState() {
super.initState();
_usersFuture = fetchAndParseUsers(); // Calls the Isolate.run method
}
@override
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:ui, rootBundle, or manipulate Flutter Widgets inside a spawned isolate. Isolates do not share memory with the main thread.dart:isolate is not supported on Flutter Web. If targeting Web, you MUST use the compute() function from package:flutter/foundation.dart instead of Isolate.run(), as compute() safely falls back to the main thread on web platforms.SendPort, prefer passing immutable objects (like Strings or unmodifiable byte data) to avoid deep-copy performance overhead.Weekly Installs
980
Repository
GitHub Stars
792
First Seen
Mar 4, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
codex946
github-copilot943
cursor943
gemini-cli942
opencode942
kimi-cli941
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
Grimoire CLI 使用指南:区块链法术编写、验证与执行全流程
940 周安装
Grimoire Uniswap 技能:查询 Uniswap 元数据与生成代币/资金池快照的 CLI 工具
940 周安装
Grimoire Aave 技能:查询 Aave V3 元数据和储备快照的 CLI 工具
941 周安装
Railway CLI 部署指南:使用 railway up 命令快速部署代码到 Railway 平台
942 周安装
n8n Python 代码节点使用指南:在自动化工作流中编写 Python 脚本
943 周安装
Flutter Platform Views 实现指南:Android/iOS/macOS原生视图与Web嵌入教程
943 周安装
dart:isolateWidgetStatefulWidgetsetStatedart:mirrors for JSON serialization. Flutter disables runtime reflection to enable aggressive tree-shaking and AOT compilation. Always use manual parsing or code generation.