flutter-use-http-package
Perform REST API networking operations (GET, POST, PUT, DELETE) using the lightweight and robust standard `http` package, including platform configurations and background parsing models.
What this skill does
## Contents
- [Configuration and Permissions](#configuration-and-permissions)
- [Request Execution and Response Handling](#request-execution-and-response-handling)
- [Background Parsing](#background-parsing)
- [Workflow: Executing Network Operations](#workflow-executing-network-operations)
- [Examples](#examples)
## Configuration and Permissions
Configure the development environment and platform-specific access controls to enable network requests:
1. Add the `http` dependency using your terminal:
```bash
flutter pub add http
```
2. Import the library with an alias in your Dart files:
```dart
import 'package:http/http.dart' as http;
```
3. Enable internet permissions on Android by modifying `android/app/src/main/AndroidManifest.xml` within the `<manifest>` tag:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
4. Enable internet clients on macOS by modifying `macos/Runner/DebugProfile.entitlements` and `macos/Runner/Release.entitlements` within the `<dict>` tag:
```xml
<key>com.apple.security.network.client</key>
<true/>
```
## Request Execution and Response Handling
Design robust REST clients by applying these best practices:
- **Strict URL Parsing**: Always parse endpoint strings via `Uri.parse('url')`. Never pass raw strings to client calls.
- **Headers and Authentication**: Attach all authorization, accept, and content-type configurations. Inject access tokens using the `HttpHeaders.authorizationHeader` key from `dart:io`.
- **Payload Encoding**: When mutating resource states (POST, PUT), encode payload bodies with `jsonEncode` from `dart:convert`.
- **Status Validation**: Verify response codes. Handle only explicit success status codes (e.g. `200 OK` or `201 Created`).
- **Throw on Errors**: Throw descriptive exceptions when the server responds with unsuccessful status codes. Never return `null` on failure, as this hides issues and results in infinite UI loading spinners.
- **Client Mocking**: Accept an `http.Client` dependency in your network classes instead of calling standard global methods. This facilitates easy testing and mock injection.
## Background Parsing
Offload JSON decoding and mapping to a background thread to prevent UI jank (dropped frames) when handling payloads larger than 1MB:
- Import `package:flutter/foundation.dart`.
- Run the parsing logic within the `compute()` function to spawn a background isolate.
- Ensure the parsing function is defined as a top-level function or static class method. Closures and standard instance methods cannot cross isolate boundaries.
## Workflow: Executing Network Operations
Follow this checklist to build and verify network integration:
- [ ] **Define model contracts**: Create clear, immutable model classes with a custom `fromJson` factory constructor.
- [ ] **Establish HTTP clients**: Build the network client class accepting `http.Client`.
- [ ] **Formulate requests**:
- [ ] For reading (GET): Attach query parameters to the URI.
- [ ] For mutations (POST/PUT): Set `'Content-Type': 'application/json; charset=UTF-8'` and attach `jsonEncode` data.
- [ ] For deletions (DELETE): Return success indicators or empty model mappings upon matching `200 OK`.
- [ ] **Enforce error handling**: Throw meaningful exceptions for non-success status codes.
- [ ] **Integrate UI state**: Bind network requests to a `FutureBuilder` or state management controller in the UI layer.
- [ ] **Verify boundaries**: Test with proper loading screens, error dialogs, and offline-handling feedback loops.
## Examples
### Complete Network Client and Isolate Parser
This example demonstrates setting up a robust, testable network client that parses complex payload lists in a background isolate.
```dart
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// 1. Top-level parsing function (required to run in a separate Isolate)
List<Product> parseProducts(String responseBody) {
final parsed = (jsonDecode(responseBody) as List<dynamic>).cast<Map<String, dynamic>>();
return parsed.map<Product>((json) => Product.fromJson(json)).toList();
}
// 2. Service Layer exposing testable methods
class ProductService {
final http.Client client;
const ProductService({required this.client});
Future<List<Product>> fetchProducts() async {
final response = await client.get(
Uri.parse('https://api.example.com/products'),
headers: {
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer token_here',
},
);
if (response.statusCode == 200) {
// Offload heavy JSON parsing of larger lists to a background isolate
return compute(parseProducts, response.body);
} else {
throw HttpException('Failed to load products. Status: ${response.statusCode}');
}
}
}
// 3. Immutable Data Model
class Product {
final int id;
final String name;
final double price;
const Product({
required this.id,
required this.name,
required this.price,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'] as int,
name: json['name'] as String,
price: (json['price'] as num).toDouble(),
);
}
}
// 4. UI Layer Integration
class ProductListView extends StatefulWidget {
final ProductService productService;
const ProductListView({
super.key,
required this.productService,
});
@override
State<ProductListView> createState() => _ProductListViewState();
}
class _ProductListViewState extends State<ProductListView> {
late Future<List<Product>> _futureProducts;
@override
void initState() {
super.initState();
// Cache the future once to prevent redundant re-fetching on rebuilds
_futureProducts = widget.productService.fetchProducts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Store Products'),
),
body: FutureBuilder<List<Product>>(
future: _futureProducts,
builder: (context, snapshot) {
if (snapshot.hasData) {
final products = snapshot.data!;
return ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
final product = products[index];
return ListTile(
title: Text(product.name),
trailing: Text('\$${product.price.toStringAsFixed(2)}'),
);
},
);
} else if (snapshot.hasError) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
'An error occurred: ${snapshot.error}',
textAlign: TextAlign.center,
),
),
);
}
return const Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
```
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.