Claude
Skills
Sign in
Back

flutter-core:flutter-data-networking

Included with Lifetime
$97 forever

Master HTTP clients, REST APIs, GraphQL integration, WebSockets, and JSON serialization in Flutter applications. Use when implementing API calls, handling network requests, parsing JSON, or working with real-time data.

Backend & APIs

What this skill does


# Flutter Data Networking

Master HTTP clients, REST APIs, GraphQL, WebSockets, and JSON serialization in Flutter applications.

## When to Use This Skill

Use this skill when working with Flutter applications that need to:

- Make HTTP requests to REST APIs or web services
- Implement GraphQL queries, mutations, or subscriptions
- Establish real-time bidirectional communication with WebSockets
- Serialize and deserialize JSON data with type safety
- Handle network errors, timeouts, and offline scenarios
- Implement authentication and authorization headers
- Build offline-first applications with data synchronization
- Upload or download files over the network
- Create robust API clients with interceptors and middleware

## Overview

Networking is fundamental to modern Flutter applications. Whether you're fetching data from a REST API, subscribing to real-time updates via WebSockets, or querying a GraphQL backend, Flutter provides powerful tools and packages to handle all networking scenarios efficiently and reliably.

This skill covers the complete spectrum of networking in Flutter, from basic HTTP requests to advanced patterns like offline-first architecture, request interceptors, and automatic retry strategies. You'll learn to choose the right networking solution for your needs and implement it following industry best practices.

## HTTP Client Packages

Flutter offers multiple HTTP client options, each suited to different use cases:

### http Package

The official `http` package is Flutter's simplest HTTP client, ideal for straightforward API calls. It provides basic GET, POST, PUT, DELETE methods with minimal configuration. Use it for simple applications or when you need a lightweight solution without advanced features.

The package is cross-platform, supporting Android, iOS, macOS, Windows, Linux, and web. However, it requires platform-specific permissions configuration, such as internet permission in AndroidManifest.xml for Android and network client entitlements for macOS.

### Dio Package

Dio is a powerful, feature-rich HTTP client that has become the industry standard for Flutter networking. It excels with:

- **Global Configuration**: Set base URLs, headers, timeouts, and other options globally for all requests
- **Interceptors**: Intercept requests, responses, and errors for logging, authentication, or transformation
- **Request Cancellation**: Cancel in-flight requests when they're no longer needed
- **FormData Support**: Upload files with multipart form data
- **Download Progress**: Track download progress for large files
- **Automatic Retries**: Configure retry logic for failed requests
- **Custom Adapters**: Replace the default HTTP adapter with custom implementations

Dio's interceptor system is particularly powerful, allowing you to implement cross-cutting concerns like JWT authentication, request logging, error handling, and response caching without duplicating code across your application.

### Choosing the Right Client

For production applications, Dio is typically the better choice due to its robust feature set and excellent error handling. Use the basic `http` package only for simple apps or quick prototypes. For enterprise applications requiring advanced features like certificate pinning, custom adapters, or sophisticated retry logic, Dio provides the necessary flexibility.

## REST API Integration

REST (Representational State Transfer) APIs are the most common backend architecture for Flutter applications. Implementing REST APIs effectively requires understanding HTTP methods, status codes, headers, and error handling.

### CRUD Operations

REST APIs typically expose four core operations (CRUD):

- **CREATE**: POST requests to create new resources
- **READ**: GET requests to retrieve existing resources
- **UPDATE**: PUT or PATCH requests to modify resources
- **DELETE**: DELETE requests to remove resources

Each operation should be wrapped in a service or repository class that handles serialization, error handling, and business logic. This separation of concerns makes your code more testable and maintainable.

### Authentication Patterns

Most production APIs require authentication, typically implemented using:

- **Bearer Tokens**: JWT tokens sent in the Authorization header
- **API Keys**: Static keys passed in headers or query parameters
- **OAuth 2.0**: Token-based authentication with refresh tokens

Dio interceptors are ideal for implementing authentication, automatically adding authentication headers to every request and handling token refresh when tokens expire.

### Error Handling

Robust error handling distinguishes production-quality apps from prototypes. Your networking layer should handle:

- **Network Errors**: Connection timeouts, DNS failures, no internet
- **HTTP Errors**: 4xx client errors, 5xx server errors
- **Serialization Errors**: Invalid JSON or schema mismatches
- **Business Logic Errors**: Application-specific error codes

Implement a consistent error handling strategy using custom exception types and a centralized error handler that can display appropriate messages to users.

## GraphQL Integration

GraphQL is an alternative to REST that allows clients to request exactly the data they need, reducing over-fetching and under-fetching. The `graphql_flutter` package provides comprehensive GraphQL support for Flutter.

### Core Concepts

GraphQL operates through three operation types:

- **Queries**: Read operations that fetch data
- **Mutations**: Write operations that create, update, or delete data
- **Subscriptions**: Real-time operations that push updates to clients

Unlike REST, GraphQL uses a single endpoint and a typed schema that defines available operations and data structures. This schema provides excellent type safety and enables powerful tooling.

### graphql_flutter Widgets

The package provides three primary widgets:

- **Query**: Executes GraphQL queries and rebuilds when data changes
- **Mutation**: Provides a callback to execute mutations
- **Subscription**: Opens a WebSocket connection for real-time updates

All widgets must be wrapped in a GraphQLProvider that configures the GraphQL client, including the endpoint URL, authentication, and caching policies.

### Caching and Optimistic Updates

graphql_flutter includes a sophisticated caching system that normalizes data by type and ID. This enables:

- **Cache-first queries**: Return cached data immediately, then update if needed
- **Optimistic updates**: Update the UI immediately, before server confirmation
- **Cache persistence**: Save cache to disk for offline access

Proper cache configuration significantly improves perceived performance and enables offline functionality.

## WebSocket Communication

WebSockets provide full-duplex communication channels over a single TCP connection, enabling real-time bidirectional data flow. They're essential for features like chat, live notifications, collaborative editing, and real-time dashboards.

### web_socket_channel Package

Flutter's `web_socket_channel` package provides a Stream-based API for WebSocket communication. The package abstracts platform differences and provides a consistent interface across all Flutter platforms.

WebSocket connections follow a lifecycle:

1. **Connection**: Establish a WebSocket connection to a URL (ws:// or wss://)
2. **Communication**: Send messages via the sink, receive via the stream
3. **Closure**: Close the connection gracefully when done

### Stream-Based Architecture

WebSockets integrate naturally with Flutter's reactive architecture through Streams. Use StreamBuilder widgets to display real-time data, and StreamControllers to manage WebSocket state in your business logic layer.

### Error Handling and Reconnection

Production WebSocket implementations must handle:

- **Connection Failures**: Network issues, server unavailability
- **Disconnections**: Unexpected connection drops
- **Reconnection Logic**: Exponential backoff for automatic reconnection

Related in Backend & APIs