pub version likes popularity pub points

Network API SDK

A production-ready Flutter networking SDK with built-in authentication, interceptors, offline caching, and request queueing — designed for scalable and enterprise-grade applications.


🤖 SDK AI Assistant

Get instant help integrating the SDK using the official AI assistant.

It can:

  • Generate ready-to-use integration code
  • Explain authentication flows
  • Debug API issues
  • Guide offline and queue behavior

Assistant:

https://chatgpt.com/g/g-69aa3c19d9e081918dafe44ed385559c-network-api-sdk-guide


Table of Contents

  1. Overview
  2. Public API Surface
  3. Installation
  4. Importing SDK
  5. Architecture
  6. Quick Start
  7. SDK Initialization
  8. SdkConfig Reference
  9. SdkProfile Reference
  10. SdkContract Reference
  11. OutputOptions Reference
  12. AuthOptions Reference
  13. HTTP Calls
  14. RequestBody Types
  15. Authentication
  16. Interceptors
  17. Response Model
  18. Error Model
  19. Events
  20. Offline Support
  21. Persistence Stores
  22. HTTP Extension Points
  23. Example Project
  24. Advanced Initialization
  25. Flow Diagrams
  26. Troubleshooting
  27. Project Status

1. Overview

Network API SDK is a standardized networking layer for Flutter applications.

It centralizes:

  • request construction
  • response normalization
  • contract-based success/error evaluation
  • authentication lifecycle
  • interceptor execution
  • offline caching
  • offline request queue
  • persistent request queue
  • queue flushing

The goal is to make API integration consistent across applications.

❓ Why Network API SDK?

  • Eliminates repetitive API boilerplate
  • Standardizes authentication and error handling
  • Provides built-in offline support and persistence
  • Ensures consistent API contracts across applications
  • Designed for enterprise-scale Flutter projects

2. Public API Surface

Core

  • Sdk
  • SdkEvents
  • SdkEvent

Configuration

  • SdkConfig
  • SdkProfile
  • SdkContract
  • OutputOptions
  • AuthOptions

Models

  • RequestBody
  • BodyFile
  • BodyType
  • ResponseTypeHint
  • SdkResponse
  • SdkError
  • ResponseSource
  • ErrorType

Authentication

  • AuthManager
  • TokenStore
  • SecureTokenStore

Interceptors

  • SdkInterceptor

HTTP Layer

  • HttpClient
  • HttpRequest
  • HttpResponse
  • DioHttpClient

Offline Layer

  • CacheStore
  • FileCacheStore
  • QueueStore
  • FileQueueStore

3. Installation

Local dependency

dependencies:
  network_api_sdk:
    path: ../network_api_sdk

Published dependency

dependencies:
  network_api_sdk: ^0.1.0

Run:

flutter pub get

4. Importing SDK

import 'package:network_api_sdk/network_api_sdk.dart';

Always import from the package root.

Avoid importing from src.


5. Architecture

SDK architecture layers:

Application Layer
        ↓
     SDK Core
        ↓
     HTTP Layer
        ↓
    Storage Layer

SDK Core Responsibilities

  • Request building
  • Response normalization
  • Authentication lifecycle
  • Contract evaluation
  • Interceptors
  • Offline orchestration

6. Quick Start

⚡ 30-Second Setup

Sdk.init(
  SdkConfig(
    baseUrl: 'https://api.example.com',
    profile: SdkProfile.defaultSecure(),
    contract: SdkContract.auto(
      data: 'data',
      message: 'message',
      successFlag: 'isSuccess',
      errorCode: 'code',
    ),
    output: OutputOptions.jsonOnly(),
  ),
);

final res = await Sdk.instance.call.get('/users');

Initialize the SDK:

Sdk.init(
  SdkConfig(
    baseUrl: 'https://api.example.com',
    profile: SdkProfile.defaultSecure(),
    contract: SdkContract.auto(
      data: 'data',
      message: 'message',
      successFlag: 'isSuccess',
      errorCode: 'code',
    ),
    output: OutputOptions.jsonOnly(),
  ),
);

Example usage:

final response = await Sdk.instance.call.get('/profile');

7. SDK Initialization

Initialize once:

Sdk.init(SdkConfig(...));

Access instance:

Sdk.instance

Available modules:

  • Sdk.instance.call
  • Sdk.instance.auth
  • Sdk.instance.events
  • Sdk.instance.http
  • Sdk.instance.cache
  • Sdk.instance.queue
  • Sdk.instance.config

8. SdkConfig Reference

Primary SDK configuration.

Example:

SdkConfig(
  baseUrl: 'https://api.example.com',
  profile: SdkProfile.defaultSecure(),
  contract: SdkContract.auto(
    data: 'data',
    message: 'message',
  ),
  output: OutputOptions.jsonOnly(),
)
Parameter Type Required Description
baseUrl String Yes API base URL
httpOverride HttpClient? No Custom HTTP client
auth AuthOptions? No Authentication configuration
tokenStoreOverride TokenStore? No Custom token storage
cacheStoreOverride CacheStore? No Custom cache store
queueStoreOverride QueueStore? No Custom queue store
profile SdkProfile Yes Offline configuration
contract SdkContract Yes API contract
output OutputOptions Yes Response normalization
interceptors List<SdkInterceptor>? No SDK interceptors

9. SdkProfile Reference

Controls offline behavior.

const SdkProfile(
  offlineEnabled: true,
  queueWritesWhenOffline: true,
  autoFlushQueue: true,
  flushInterval: null,
)
Field Type Description
offlineEnabled bool Enable offline features
queueWritesWhenOffline bool Queue writes when offline
autoFlushQueue bool Flush the queue once on init when flushInterval is null
flushInterval Duration? Reserved for future scheduled flushing; not used by the built-in flow yet

Factories:

SdkProfile.defaultSecure();
SdkProfile.offlineFirstSecure();

10. SdkContract Reference

Defines backend response structure.

SdkContract.auto(
  data: 'data',
  message: 'message',
  successFlag: 'isSuccess',
  errorCode: 'code',
)

Fallback error path:

errors[0].message

11. OutputOptions Reference

Controls SDK output format.

OutputOptions.jsonOnly();

Advanced:

OutputOptions.jsonOnly(
  tryParseJsonText: true,
  bytesMode: BytesJsonMode.base64,
);

12. AuthOptions Reference

AuthOptions(
  loginEndpoint: '/auth/login',
  refreshEndpoint: '/auth/refresh',
  accessTokenPath: 'accessToken',
  refreshTokenPath: 'refreshToken',
);
Field Type Description
loginEndpoint String Login API
refreshEndpoint String Refresh API
accessTokenPath String Access token path
refreshTokenPath String Refresh token path
refreshRequestKey String Refresh body key, defaults to refreshToken

13. HTTP Calls

Main entry:

Sdk.instance.call

Methods:

  • get
  • post
  • put
  • delete
  • any

Example:

final res = await Sdk.instance.call.get('/users');

HTTP Call Parameters

Parameter Type Required Description
endpoint String Yes API endpoint path
query Map<String, dynamic>? No Query parameters
headers Map<String, String>? No Request headers
body RequestBody? No Request payload
responseType ResponseTypeHint? No Expected response type
attachAuth bool No Whether to attach bearer token

14. RequestBody Types

Constructors:

RequestBody.none()
RequestBody.json()
RequestBody.text()
RequestBody.bytes()
RequestBody.formUrlEncoded()
RequestBody.multipart()

Example:

RequestBody.json({
  'email': 'a@b.com',
});

BodyFile

Used in multipart uploads.

Field Type Description
filename String File name
bytes Uint8List File data
contentType String? MIME type

15. Authentication

Login example:

await Sdk.instance.auth.login(
  body: {
    'username': 'user',
    'password': 'password',
  },
  rememberMe: true,
);

Login parameters

Parameter Type Description
body Map Login payload
headers Map? Extra headers
rememberMe bool Persist tokens

Sign Out

await Sdk.instance.auth.signOut();

16. Interceptors

Example:

class MyInterceptor implements SdkInterceptor {
  @override
  Future<HttpRequest?> onRequest(HttpRequest req) async => req;

  @override
  Future<HttpResponse?> onResponse(HttpRequest req, HttpResponse res) async => res;

  @override
  Future<SdkError?> onError(HttpRequest req, SdkError error) async => error;
}

Register:

interceptors: [
  MyInterceptor(),
]

17. Response Model

SDK responses return SdkResponse.

Example:

if (res.ok) {
  print(res.data);
}
Field Type
ok bool
data dynamic
error SdkError?
statusCode int
message String?
source ResponseSource

ResponseSource

  • network
  • cache
  • queued

18. Error Model

SDK errors return SdkError.

Field Type
type ErrorType
message String
statusCode int?
raw dynamic

ErrorType

  • offline
  • timeout
  • unauthorized
  • forbidden
  • badRequest
  • server
  • contract
  • parse
  • unknown

19. Events

Listen:

Sdk.instance.events.stream.listen((event) {
  // handle event
});

Events:

  • sessionExpired
  • signedOut

20. Offline Support

When enabled:

  • GET → cache fallback
  • WRITE → queued request

Manual queue flush:

await Sdk.instance.queue.flush();

21. Persistence Stores

Tokens

  • TokenStore
  • SecureTokenStore

Cache

  • CacheStore
  • FileCacheStore

Queue

  • QueueStore
  • FileQueueStore

22. HTTP Extension Points

Default client:

DioHttpClient

Constructor:

DioHttpClient(
  baseUrl: 'https://api.example.com',
  connectTimeout: Duration(seconds: 20),
  receiveTimeout: Duration(seconds: 30),
);

23. Example Project

Located in:

/example

Run:

cd example
flutter pub get
flutter run

24. Advanced Initialization

Offline-first configuration:

Sdk.init(
  SdkConfig(
    baseUrl: 'https://api.example.com',
    profile: SdkProfile.offlineFirstSecure(),
    contract: SdkContract.auto(
      data: 'data',
      message: 'message',
    ),
    output: OutputOptions.jsonOnly(),
  ),
);

25. Flow Diagrams

Authentication flow:

Login
 ↓
Save Tokens
 ↓
Attach Bearer
 ↓
401
 ↓
Refresh
 ↓
Retry Request

Offline queue flow:

Write Request
 ↓
No Internet
 ↓
Queue
 ↓
Persist
 ↓
Flush Later

26. Troubleshooting

SDK not initialized:

Sdk.init(
  SdkConfig(
    baseUrl: 'https://api.example.com',
    profile: SdkProfile.defaultSecure(),
    contract: SdkContract.auto(
      data: 'data',
      message: 'message',
    ),
    output: OutputOptions.jsonOnly(),
  ),
);

Refresh token failing:

Check:

  • refreshEndpoint
  • refreshTokenPath
  • accessTokenPath

27. Project Status

Implemented

  • SDK initialization
  • contract parsing
  • authentication login
  • refresh token
  • bearer token attach
  • interceptors
  • offline cache
  • offline queue
  • queue persistence
  • manual queue flush
  • auto flush on init
  • SDK events

Planned

  • retry policies
  • observability
  • upload progress
  • cache invalidation
  • advanced queue policies

Libraries

network_api_sdk
Public entry point for the network_api_sdk package.