원클릭으로
flutter-http-and-json
Make HTTP requests and encode / decode JSON in a Flutter app
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
메뉴
Make HTTP requests and encode / decode JSON in a Flutter app
Codex 또는 Claude로 설치 이 Prompt를 복사해 Codex, Claude 또는 다른 어시스턴트에 붙여 넣으면 Skill 페이지를 검토하고 설치를 진행할 수 있습니다.
SOC 직업 분류 기준
PocketMind 本地无头浏览器爬取架构,适用于小红书/知乎抓取、后台爬虫服务、MethodChannel、Cookie 管理与 MetadataManager 协作场景。
Use when implementing or debugging PocketMind mobile chat flows, including note-scoped sessions, global multi-session switching, sync gating, stream send behavior, and dialog interaction regressions.
PocketMind 后端 notes->resource_records->context_catalog 一致性改造专项 Skill。当用户讨论 resource_records 真相层、context_catalog 索引层、Outbox/Projector、检索 fallback、SessionCommit 长事务、transcript 重复同步或相关回归测试时必须触发。
Use when you need to understand or modify PocketMind note save to resource indexing flow, including outbox, MQ hint/DLQ compensation, projector consumption, and consistency boundaries.
PocketMind 移动端笔记同步架构专项 Skill。当涉及以下问题时必须触发:预览字段(previewTitle等)被同步覆盖、多端一致性与离线冲突问题、同步链路改造(Pull/Push)、UI层违规调用底层Provider、抓取/轮询等写入未进入同步队列、或维护同步守卫测试。
设计、重构和实现 PocketMind 项目中的整体上下文架构(Context Architecture),用于统一规划和落地 resources、user memories、agent memories、tenant skills、session、retrieval、ingestion、storage 与现有 Note/Chat/Asset 的边界。当用户要求为 PocketMind 新增长期记忆、重构 AI 上下文体系、借鉴 OpenViking 的上下文类型/层级/URI/存储/检索/会话思想,或需要分阶段实施 Context Service 时使用。
| name | flutter-http-and-json |
| description | Make HTTP requests and encode / decode JSON in a Flutter app |
| metadata | {"model":"models/gemini-3.1-pro-preview","last_modified":"Wed, 04 Mar 2026 17:55:17 GMT"} |
Manages HTTP networking and JSON data handling in Flutter applications. Implements secure, asynchronous REST API calls (GET, POST, PUT, DELETE) using the http package. Handles JSON serialization, background parsing via isolates for large datasets, and structured JSON schemas for AI model integrations. Assumes the http package is added to pubspec.yaml and the environment supports Dart 3 pattern matching and null safety.
When implementing JSON parsing and serialization, evaluate the following decision tree:
compute() to avoid UI jank.dart:convert).json_serializable and build_runner for automated code generation?"Before making network requests, ensure the target platforms have the required internet permissions.
Android (android/app/src/main/AndroidManifest.xml):
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
<application ...>
</manifest>
macOS (macos/Runner/DebugProfile.entitlements and Release.entitlements):
<dict>
<!-- Required to fetch data from the internet. -->
<key>com.apple.security.network.client</key>
<true/>
</dict>
Create a strongly typed Dart class to represent the JSON data. Use factory constructors for deserialization and a toJson method for serialization.
import 'dart:convert';
class ItemModel {
final int id;
final String title;
const ItemModel({required this.id, required this.title});
// Deserialize using Dart 3 pattern matching
factory ItemModel.fromJson(Map<String, dynamic> json) {
return switch (json) {
{'id': int id, 'title': String title} => ItemModel(id: id, title: title),
_ => throw const FormatException('Failed to parse ItemModel.'),
};
}
// Serialize to JSON
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
};
}
Use the http package to perform network requests. Always use Uri.https for safe URL encoding. Validate the status code and throw exceptions on failure.
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final http.Client client;
ApiService(this.client);
// GET Request
Future<ItemModel> fetchItem(int id) async {
final uri = Uri.https('api.example.com', '/items/$id');
final response = await client.get(uri);
if (response.statusCode == 200) {
return ItemModel.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
throw Exception('Failed to load item: ${response.statusCode}');
}
}
// POST Request
Future<ItemModel> createItem(String title) async {
final uri = Uri.https('api.example.com', '/items');
final response = await client.post(
uri,
headers: <String, String>{'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(<String, String>{'title': title}),
);
if (response.statusCode == 201) {
return ItemModel.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
} else {
throw Exception('Failed to create item: ${response.statusCode}');
}
}
// DELETE Request
Future<void> deleteItem(int id) async {
final uri = Uri.https('api.example.com', '/items/$id');
final response = await client.delete(
uri,
headers: <String, String>{'Content-Type': 'application/json; charset=UTF-8'},
);
if (response.statusCode != 200) {
throw Exception('Failed to delete item: ${response.statusCode}');
}
}
}
If fetching a large list of objects, move the JSON decoding and mapping to a separate isolate using compute().
import 'package:flutter/foundation.dart';
// Top-level function required for compute()
List<ItemModel> parseItems(String responseBody) {
final parsed = (jsonDecode(responseBody) as List<Object?>).cast<Map<String, Object?>>();
return parsed.map<ItemModel>(ItemModel.fromJson).toList();
}
Future<List<ItemModel>> fetchLargeItemList(http.Client client) async {
final uri = Uri.https('api.example.com', '/items');
final response = await client.get(uri);
if (response.statusCode == 200) {
// Run parseItems in a separate isolate
return compute(parseItems, response.body);
} else {
throw Exception('Failed to load items');
}
}
When integrating LLMs (like Gemini), enforce reliable JSON output by passing a strict schema in the generation configuration and system instructions.
import 'package:firebase_vertexai/firebase_vertexai.dart';
// Define the expected JSON schema
final _responseSchema = Schema(
SchemaType.object,
properties: {
'width': Schema(SchemaType.integer),
'height': Schema(SchemaType.integer),
'items': Schema(
SchemaType.array,
items: Schema(
SchemaType.object,
properties: {
'id': Schema(SchemaType.integer),
'name': Schema(SchemaType.string),
},
),
),
},
);
// Initialize the model with the schema
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-2.5-pro',
generationConfig: GenerationConfig(
responseMimeType: 'application/json',
responseSchema: _responseSchema,
),
);
Future<Map<String, dynamic>> analyzeData(String prompt) async {
final content = [Content.text(prompt)];
final response = await model.generateContent(content);
// Safely decode the guaranteed JSON response
return jsonDecode(response.text!) as Map<String, dynamic>;
}
Uri.https() or Uri.parse() to build URLs. Never use raw string concatenation for endpoints with query parameters.null on a failed network request. Always throw an Exception or a custom error class so the UI (e.g., FutureBuilder) can catch and display the error state via snapshot.hasError.response.statusCode. Use 200 for successful GET/PUT/DELETE and 201 for successful POST.dart:io HttpClient directly for standard cross-platform networking. Always use the http package to ensure web compatibility.compute(), ensure the parsing function is a top-level function or a static method, and only pass primitive values or simple objects (like String response bodies) across the isolate boundary. Do not pass http.Response objects.