### Initialize DioHttpCache Example Application Source: https://pub.dev/packages/dio_http_cache/example The main entry point for the example app, setting up the MaterialApp and a stateful widget to switch between different cache demonstration panels. ```dart import 'package:flutter/material.dart'; import 'panels/cache_manage.dart'; import 'panels/panel_204.dart'; import 'panels/panel_get.dart'; import 'panels/panel_get_bytes.dart'; import 'panels/panel_get_from_service.dart'; import 'panels/panel_post.dart'; import 'tuple.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final title = "DioHttpCache Example"; return MaterialApp( title: title, theme: ThemeData(primarySwatch: Colors.blue), home: MyHomePage(title: title)); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, this.title}) : super(key: key); final String? title; @override _MyHomePageState createState() => _MyHomePageState(); } enum Panel { CACHE_MANAGER, POST, POST_204, GET_FROM_SERVICE, GET, GET_BYTES } class _MyHomePageState extends State { Panel panel = Panel.POST; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title!), actions: [_buildHomePageActionButtons(context)]), body: getPanel()); } Widget? getPanel() { switch (panel) { case Panel.CACHE_MANAGER: return CacheManagerPanel(); case Panel.GET: return GetPanel(); case Panel.POST: return PostPanel(); case Panel.POST_204: return Post204Panel(); case Panel.GET_FROM_SERVICE: return PostGetLetServicePanel(); case Panel.GET_BYTES: return GetBytesPanel(); } } Widget _buildHomePageActionButtons(BuildContext context) { List> choices = [ Pair("Cache Manager", () => setState(() => panel = Panel.CACHE_MANAGER)), Pair("POST", () => setState(() => panel = Panel.POST)), Pair("POST 204", () => setState(() => panel = Panel.POST_204)), Pair("GET", () => setState(() => panel = Panel.GET)), Pair("GET from service", () => setState(() => panel = Panel.GET_FROM_SERVICE)), Pair("GET byte array", () => setState(() => panel = Panel.GET_BYTES)), ]; return PopupMenuButton>( onSelected: (p) => p.i1!(), child: Padding( padding: EdgeInsets.all(10), child: Icon(Icons.menu, color: Colors.white)), itemBuilder: (BuildContext context) => choices .map((choice) => PopupMenuItem>( value: choice, child: Text(choice.i0!))) .toList()); } } ``` -------------------------------- ### Install ObjectBox Native Library Source: https://pub.dev/packages/dio_cache_interceptor_objectbox_store Run this command on your host machine to install the native ObjectBox library required for running unit tests. ```bash bash <(curl -s https://raw.githubusercontent.com/objectbox/objectbox-dart/main/install.sh) ``` -------------------------------- ### Install diox_http2_adapter Source: https://pub.dev/packages/diox_http2_adapter Add the dependency to your pubspec.yaml file. ```yaml dependencies: diox_http2_adapter: ^2.0.0 # latest version ``` -------------------------------- ### Initialize Dio with Http2Adapter Source: https://pub.dev/packages/dio_http2_adapter Basic setup for integrating the Http2Adapter into a Dio instance. ```dart import 'package:dio/dio.dart'; import 'package:dio_http2_adapter/dio_http2_adapter.dart'; void main() async { final dio = Dio() ..options.baseUrl = 'https://pub.dev' ..interceptors.add(LogInterceptor()) ..httpClientAdapter = Http2Adapter( ConnectionManager(idleTimeout: Duration(seconds: 10)), ); Response response; response = await dio.get('/?xx=6'); for (final e in response.redirects) { print('redirect: ${e.statusCode} ${e.location}'); } print(response.data); } ``` -------------------------------- ### Perform GET requests with Dio Source: https://pub.dev/packages/diox Demonstrates how to perform GET requests using direct URL parameters or the queryParameters map. ```dart import 'package:diox/diox.dart'; final dio = Dio(); void request() async { Response response; response = await dio.get('/test?id=12&name=dio'); print(response.data.toString()); // The below request is the same as above. response = await dio.get( '/test', queryParameters: {'id': 12, 'name': 'dio'}, ); print(response.data.toString()); } ``` -------------------------------- ### GET Request Response Source: https://pub.dev/packages/dio Example of performing a GET request and accessing the properties of the returned Response object. ```APIDOC ## GET Request ### Description Performs a GET request and demonstrates how to access the response data, headers, request options, and status code. ### Request Example ```dart final response = await dio.get('https://pub.dev'); print(response.data); print(response.headers); print(response.requestOptions); print(response.statusCode); ``` ### Response Properties - **data** (T?) - The response body, potentially transformed. - **requestOptions** (RequestOptions) - The corresponding request configuration. - **statusCode** (int?) - The HTTP status code. - **statusMessage** (String?) - The reason phrase associated with the status code. - **isRedirect** (bool) - Indicates if the response is a redirect. - **redirects** (List) - The series of redirects followed. - **extra** (Map) - Custom fields specific to the Response. - **headers** (Headers) - The response headers. ``` -------------------------------- ### Perform a basic HTTP GET request with Dio Source: https://pub.dev/packages/dio/example Initializes a Dio instance and performs a GET request to a specified URL. ```dart import 'package:dio/dio.dart'; /// More examples see https://github.com/cfug/dio/tree/main/dio#examples void main() async { final dio = Dio(); final response = await dio.get('https://pub.dev'); print(response.data); } ``` -------------------------------- ### Install diox_cookie_manager Source: https://pub.dev/packages/diox_cookie_manager Add the dependency to your pubspec.yaml file. ```yaml dependencies: diox_cookie_manager: ^2.0.0 # latest version ``` -------------------------------- ### Perform a basic HTTP request Source: https://pub.dev/packages/diox Example of using the request method to send data with specific options. ```dart final response = await dio.request( '/test', data: {'id': 12, 'name': 'dio'}, options: Options(method: 'GET'), ); ``` -------------------------------- ### Install diox_flutter_transformer Source: https://pub.dev/packages/diox_flutter_transformer Add the package to your pubspec.yaml dependencies. ```yaml dependencies: diox_flutter_transformer: ^1.0.1 # latest version ``` -------------------------------- ### Install dio_http_cache via command line Source: https://pub.dev/packages/dio_http_cache/install Use this command in your terminal to add the package to your Flutter project. ```bash $ flutter pub add dio_http_cache ``` -------------------------------- ### Access response data Source: https://pub.dev/packages/diox Example of retrieving information from a successful GET request. ```dart final response = await dio.get('https://pub.dev'); print(response.data); print(response.headers); print(response.requestOptions); print(response.statusCode); ``` -------------------------------- ### Perform GET requests with query parameters Source: https://pub.dev/packages/dio Demonstrates two ways to pass query parameters: directly in the URL string or via the queryParameters map. ```dart import 'package:dio/dio.dart'; final dio = Dio(); void request() async { Response response; response = await dio.get('/test?id=12&name=dio'); print(response.data.toString()); // The below request is the same as above. response = await dio.get( '/test', queryParameters: {'id': 12, 'name': 'dio'}, ); print(response.data.toString()); } ``` -------------------------------- ### Static Analysis: pubspec.yaml Warning Source: https://pub.dev/packages/dio_http_cache/score Example of a warning regarding the deprecated 'authors' field in the pubspec.yaml file. ```yaml ╷ 4 │ authors: │ ^^^^^^^ ╵ ``` -------------------------------- ### Flutter Persistent Storage Setup Source: https://pub.dev/packages/diox_cookie_manager Configure PersistCookieJar with a valid file path using path_provider in a Flutter application. ```dart Future prepareJar() async { final Directory appDocDir = await getApplicationDocumentsDirectory(); final String appDocPath = appDocDir.path; final jar = PersistCookieJar( ignoreExpires: true, storage: FileStorage(appDocPath +"/.cookies/" ), ); dio.interceptors.add(CookieManager(jar)); } ``` -------------------------------- ### Static Analysis: typedef Syntax Info Source: https://pub.dev/packages/dio_http_cache/score Example of an informational message regarding the use of generic function type syntax in typedefs. ```dart ╷ 3 │ typedef Future> Encrypt(List str); │ ^^^^^^^ ╵ ``` -------------------------------- ### Create and configure a Dio instance Source: https://pub.dev/packages/diox Demonstrates initializing Dio with default options or a custom BaseOptions object. ```dart final dio = Dio(); // With default `Options`. void configureDio() { // Set default configs dio.options.baseUrl = 'https://api.pub.dev'; dio.options.connectTimeout = Duration(seconds: 5); dio.options.receiveTimeout = Duration(seconds: 3); // Or create `Dio` with a `BaseOptions` instance. final options = BaseOptions( baseUrl: 'https://api.pub.dev', connectTimeout: Duration(seconds: 5), receiveTimeout: Duration(seconds: 3), ); final anotherDio = Dio(options); } ``` -------------------------------- ### Configure Dio Instance Source: https://pub.dev/packages/dio Demonstrates creating a Dio instance with default settings, configuring options post-initialization, and cloning existing instances. ```dart final dio = Dio(); // With default `Options`. void configureDio() { // Set default configs dio.options.baseUrl = 'https://api.pub.dev'; dio.options.connectTimeout = Duration(seconds: 5); dio.options.receiveTimeout = Duration(seconds: 3); // Or create `Dio` with a `BaseOptions` instance. final options = BaseOptions( baseUrl: 'https://api.pub.dev', connectTimeout: Duration(seconds: 5), receiveTimeout: Duration(seconds: 3), ); final anotherDio = Dio(options); // Or clone the existing `Dio` instance with all fields. final clonedDio = dio.clone(); } ``` -------------------------------- ### Instantiate HttpClientAdapter Source: https://pub.dev/packages/diox/changelog Use this syntax to instantiate a platform-independent HTTP client adapter. ```dart dio.httpClientAdapter = HttpClientAdapter(); ``` -------------------------------- ### Configure Dio with Http2Adapter Source: https://pub.dev/packages/dio_http2_adapter/example Initializes a Dio instance with the Http2Adapter and a custom ConnectionManager. Ensure the dio and dio_http2_adapter packages are imported. ```dart import 'package:dio/dio.dart'; import 'package:dio_http2_adapter/dio_http2_adapter.dart'; void main() async { final dio = Dio() ..options.baseUrl = 'https://pub.dev' ..interceptors.add(LogInterceptor()) ..httpClientAdapter = Http2Adapter( ConnectionManager(idleTimeout: const Duration(seconds: 10)), ); Response response; response = await dio.get('/?xx=6'); for (final e in response.redirects) { print('redirect: ${e.statusCode} ${e.location}'); } print(response.data); } ``` -------------------------------- ### Configure a custom Dio client Source: https://pub.dev/packages/dio_image_provider Demonstrates how to set a global Dio instance or provide a specific instance via the constructor. ```dart // Either by setting it globally DioImage.defaultDio = Dio(); // or by supplying it via constructor Image( image: DioImage( Uri.parse('https://http.cat/200'), dio: Dio(), ), ) ``` -------------------------------- ### Dio() Source: https://pub.dev/packages/dio/versions/5.10.0 Initializes a new Dio instance with optional BaseOptions for global configuration such as baseUrl, connectTimeout, and receiveTimeout. ```APIDOC ## Dio Constructor ### Description Creates a new instance of the Dio HTTP client. It is recommended to use a singleton instance to manage configurations consistently. ### Usage ```dart final dio = Dio(); final options = BaseOptions(baseUrl: 'https://api.pub.dev', connectTimeout: Duration(seconds: 5)); final anotherDio = Dio(options); ``` ``` -------------------------------- ### Basic Cookie Management with Dio Source: https://pub.dev/packages/dio_cookie_manager/example Demonstrates how to initialize a CookieJar and add it to Dio's interceptors to automatically manage cookies across requests. ```dart import 'package:cookie_jar/cookie_jar.dart'; import 'package:dio/dio.dart'; import 'package:dio_cookie_manager/dio_cookie_manager.dart'; void main() async { final dio = Dio(); final cookieJar = CookieJar(); dio.interceptors.add(CookieManager(cookieJar)); await dio.get('https://baidu.com/'); // Print cookies print(cookieJar.loadForRequest(Uri.parse('https://baidu.com/'))); // second request with the cookie await dio.get('https://baidu.com/'); } ``` -------------------------------- ### Configure Proxy with IOHttpClientAdapter Source: https://pub.dev/packages/dio Uses the createHttpClient callback to define a proxy for native platform requests. ```dart import 'package:dio/io.dart'; void initAdapter() { dio.httpClientAdapter = IOHttpClientAdapter( createHttpClient: () { final client = HttpClient(); // Config the client. client.findProxy = (uri) { // Forward all request to proxy "localhost:8888". // Be aware, the proxy should went through you running device, // not the host platform. return 'PROXY localhost:8888'; }; // You can also create a new HttpClient for Dio instead of returning, // but a client must being returned here. return client; }, ); } ``` -------------------------------- ### Initialize DioCacheInterceptor in Flutter Source: https://pub.dev/packages/dio_cache_interceptor/example Demonstrates setting up the Dio client with cache options and a memory-based cache store in a StatefulWidget. ```dart // import 'dart:io'; import 'dart:ui'; import 'package:dio/dio.dart'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; // import 'package:path_provider/path_provider.dart' as pp; import 'caller.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State createState() => _MyAppState(); } class _MyAppState extends State { late CacheStore cacheStore; late CacheOptions cacheOptions; late Dio dio; late Caller caller; @override void initState() { cacheStore = MemCacheStore(maxSize: 10485760, maxEntrySize: 1048576); cacheOptions = CacheOptions( store: cacheStore, hitCacheOnNetworkFailure: true, // for offline behaviour ); dio = Dio()..interceptors.add(DioCacheInterceptor(options: cacheOptions)); // or // pp.getTemporaryDirectory().then((dir) { // cacheStore = FileCacheStore(dir.path); // // or // cacheStore = DbCacheStore(databasePath: dir.path, logStatements: true); // cacheStore = HiveCacheStore(dir.path); // cacheOptions = CacheOptions( // store: cacheStore, // hitCacheOnErrorExcept: [], // for offline behaviour // ); // dio = Dio() // ..interceptors.add( // DioCacheInterceptor(options: cacheOptions), // ); // }); caller = Caller( cacheStore: cacheStore, cacheOptions: cacheOptions, dio: dio, ); super.initState(); } @override void dispose() async { dio.close(); await cacheStore.close(); return super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Dio cache interceptor', home: DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: const Text('Dio cache interceptor'), bottom: const TabBar( tabs: [ Tab( child: Text('With server cache', textAlign: TextAlign.center), ), Tab( child: Text( 'Without server cache', textAlign: TextAlign.center, ), ), Tab(child: Text('Image')), ], ), ), body: TabBarView( children: [ _WithCacheTab(caller), _WithoutCacheTab(caller), _ImageCacheTab(caller), ], ), ), ), ); } } class _WithCacheTab extends StatefulWidget { const _WithCacheTab(this.caller); final Caller caller; @override _WithCacheTabState createState() => _WithCacheTabState(); } class _WithCacheTabState extends State<_WithCacheTab> { String text = ''; final url = 'https://www.wikipedia.org'; ``` -------------------------------- ### Configure and use DioCacheInterceptor Source: https://pub.dev/packages/dio_cache_interceptor Demonstrates how to initialize global CacheOptions, add the interceptor to a Dio instance, and perform cached requests with policy overrides. ```dart import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; // Global options final options = const CacheOptions( // A default store is required for interceptor. store: MemCacheStore(), // All subsequent fields are optional to get a standard behaviour. // Default. policy: CachePolicy.request, // Returns a cached response on error for given status codes. // Defaults to `[]`. hitCacheOnErrorCodes: [500], // Allows to return a cached response on network errors (e.g. offline usage). // Defaults to `false`. hitCacheOnNetworkFailure: true, // Overrides any HTTP directive to delete entry past this duration. // Useful only when origin server has no cache config or custom behaviour is desired. // Defaults to `null`. maxStale: const Duration(days: 7), // Default. Allows 3 cache sets and ease cleanup. priority: CachePriority.normal, // Default. Body and headers encryption with your own algorithm. cipher: null, // Default. Key builder to retrieve requests. keyBuilder: CacheOptions.defaultCacheKeyBuilder, // Default. Allows to cache POST requests. // Assigning a [keyBuilder] is strongly recommended when `true`. allowPostMethod: false, ); // Add cache interceptor with global/default options final dio = Dio()..interceptors.add(DioCacheInterceptor(options: options)); // ... // Requesting with global options => status(200) => Content is written to cache store. var response = await dio.get('https://www.foo.com'); // Requesting with global options => status(304 => 200) => Content is read from cache store. response = await dio.get('https://www.foo.com'); // Requesting by modifying policy with refresh option // for this single request => status(200) => Content is written to cache store. response = await dio.get('https://www.foo.com', options: options.copyWith(policy: CachePolicy.refresh).toOptions(), ); ``` -------------------------------- ### Handle DioException errors Source: https://pub.dev/packages/dio Use a try-catch block to handle DioException. Check the response property to distinguish between server-side errors and request setup issues. ```dart try { // 404 await dio.get('https://api.pub.dev/not-exist'); } on DioException catch (e) { // The request was made and the server responded with a status code // that falls out of the range of 2xx and is also not 304. if (e.response != null) { print(e.response.data) print(e.response.headers) print(e.response.requestOptions) } else { // Something happened in setting up or sending the request that triggered an Error print(e.requestOptions) print(e.message) } } ``` -------------------------------- ### Initialize ObjectBoxCacheStore with Dio Source: https://pub.dev/packages/dio_cache_interceptor_objectbox_store/example Configures the ObjectBox cache store using a temporary directory and adds it to the Dio interceptor chain. ```dart import 'package:dio/dio.dart'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:dio_cache_interceptor_objectbox_store/dio_cache_interceptor_objectbox_store.dart'; import 'package:path_provider/path_provider.dart'; void main(List arguments) { // Full example is available at // https://github.com/llfbandit/dio_cache_interceptor/blob/master/dio_cache_interceptor/example/lib/main.dart late CacheStore cacheStore; getTemporaryDirectory().then((dir) { cacheStore = ObjectBoxCacheStore(storePath: dir.path); var cacheOptions = CacheOptions( store: cacheStore, hitCacheOnErrorExcept: [], // for offline behaviour ); final dio = Dio() ..interceptors.add( DioCacheInterceptor(options: cacheOptions), ); dio.get('https://www.foo.com'); }); } ``` -------------------------------- ### Configure Dio for Web Source: https://pub.dev/packages/dio_web_adapter/example Sets up the Dio client to use the BrowserHttpClientAdapter, which is required for web-specific HTTP requests. ```dart import 'package:dio/dio.dart'; import 'package:dio_web_adapter/dio_web_adapter.dart'; void main() { final dio = Dio(); dio.httpClientAdapter = BrowserHttpClientAdapter(withCredentials: true); dio.interceptors.add(LogInterceptor()); dio.get('https://httpbun.com/status/200'); } ``` -------------------------------- ### Analyze browser adapter code Source: https://pub.dev/packages/diox/score Command to run static analysis on the browser adapter file to identify deprecated imports. ```bash dart analyze lib/src/adapters/browser_adapter.dart ``` -------------------------------- ### Add dependency via command line Source: https://pub.dev/packages/dio_cache_interceptor_isar_store/install Use these commands to add the package to your project using the Dart or Flutter CLI. ```bash $ dart pub add dio_cache_interceptor_isar_store ``` ```bash $ flutter pub add dio_cache_interceptor_isar_store ``` -------------------------------- ### Initialize HiveCacheStore with Dio Source: https://pub.dev/packages/dio_cache_interceptor_hive_store/example Configures a Hive-based cache store using a temporary directory and adds it to the Dio interceptor chain. ```dart import 'package:dio/dio.dart'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_store.dart'; import 'package:path_provider/path_provider.dart'; void main(List arguments) { // Full example is available at // https://github.com/llfbandit/dio_cache_interceptor/blob/master/dio_cache_interceptor/example/lib/main.dart late CacheStore cacheStore; getTemporaryDirectory().then((dir) { cacheStore = HiveCacheStore(dir.path); var cacheOptions = CacheOptions( store: cacheStore, hitCacheOnErrorExcept: [], // for offline behaviour ); final dio = Dio() ..interceptors.add( DioCacheInterceptor(options: cacheOptions), ); dio.get('https://www.foo.com'); }); } ``` -------------------------------- ### Initialize DbCacheStore with Dio Source: https://pub.dev/packages/dio_cache_interceptor_db_store/example Configures a Dio instance to use the DbCacheStore for persistent caching, requiring a valid directory path for the database file. ```dart import 'package:dio/dio.dart'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:dio_cache_interceptor_db_store/dio_cache_interceptor_db_store.dart'; import 'package:path_provider/path_provider.dart'; void main(List arguments) { // Full example is available at // https://github.com/llfbandit/dio_cache_interceptor/blob/master/dio_cache_interceptor/example/lib/main.dart late CacheStore cacheStore; getTemporaryDirectory().then((dir) { cacheStore = DbCacheStore(databasePath: dir.path, logStatements: true); var cacheOptions = CacheOptions( store: cacheStore, hitCacheOnErrorExcept: [], // for offline behaviour ); final dio = Dio() ..interceptors.add( DioCacheInterceptor(options: cacheOptions), ); dio.get('https://www.foo.com'); }); } ``` -------------------------------- ### Add dependency via command line Source: https://pub.dev/packages/diox/install Use these commands to add the diox package to your project dependencies. ```bash $ dart pub add diox ``` ```bash $ flutter pub add diox ``` -------------------------------- ### Analyze compute utility code Source: https://pub.dev/packages/diox/score Command to run static analysis on the compute utility file to identify documentation issues. ```bash dart analyze lib/src/compute/compute.dart ``` -------------------------------- ### Add dependency via command line Source: https://pub.dev/packages/dio_cache_interceptor_db_store/install Use these commands to add the package to your project dependencies automatically. ```bash $ dart pub add dio_cache_interceptor_db_store ``` ```bash $ flutter pub add dio_cache_interceptor_db_store ``` -------------------------------- ### Add dependency via command line Source: https://pub.dev/packages/dio_cache_interceptor/install Use these commands to add the package to your project dependencies automatically. ```bash $ dart pub add dio_cache_interceptor ``` ```bash $ flutter pub add dio_cache_interceptor ``` -------------------------------- ### Add dependency via command line Source: https://pub.dev/packages/dio_cache_interceptor_file_store/install Use these commands to add the package to your project dependencies automatically. ```bash $ dart pub add dio_cache_interceptor_file_store ``` ```bash $ flutter pub add dio_cache_interceptor_file_store ``` -------------------------------- ### Initialize SembastCacheStore with Dio Source: https://pub.dev/packages/dio_cache_interceptor_sembast_storage/example Configures a Dio instance to use Sembast for caching by providing a store path via path_provider. ```dart import 'package:dio/dio.dart'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:dio_cache_interceptor_sembast_store/dio_cache_interceptor_sembast_store.dart'; import 'package:path_provider/path_provider.dart'; void main(List arguments) { // Full example is available at // https://github.com/llfbandit/dio_cache_interceptor/blob/master/dio_cache_interceptor/example/lib/main.dart late CacheStore cacheStore; getTemporaryDirectory().then((dir) { cacheStore = SembastCacheStore(storePath: dir.path); var cacheOptions = CacheOptions( store: cacheStore, hitCacheOnErrorExcept: [], // for offline behaviour ); final dio = Dio() ..interceptors.add( DioCacheInterceptor(options: cacheOptions), ); dio.get('https://www.foo.com'); }); } ``` -------------------------------- ### Initialize FileCacheStore with Dio Source: https://pub.dev/packages/dio_cache_interceptor_file_store/example Configures a Dio instance to use FileCacheStore for caching requests in the application's temporary directory. ```dart import 'package:dio/dio.dart'; import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; import 'package:dio_cache_interceptor_file_store/dio_cache_interceptor_file_store.dart'; import 'package:path_provider/path_provider.dart'; void main(List arguments) { // Full example is available at // https://github.com/llfbandit/dio_cache_interceptor/blob/master/dio_cache_interceptor/example/lib/main.dart late CacheStore cacheStore; getTemporaryDirectory().then((dir) { cacheStore = FileCacheStore(dir.path); var cacheOptions = CacheOptions( store: cacheStore, hitCacheOnErrorExcept: [], // for offline behaviour ); final dio = Dio() ..interceptors.add( DioCacheInterceptor(options: cacheOptions), ); dio.get('https://www.foo.com'); }); } ``` -------------------------------- ### Check package dependencies Source: https://pub.dev/packages/diox/score Command to check for outdated dependencies in the package. ```bash dart pub outdated --no-dev-dependencies --up-to-date --no-dependency-overrides ``` -------------------------------- ### Implement a Custom Dio Client Source: https://pub.dev/packages/diox Use the DioMixin to implement a custom Dio client when direct extension is not suitable. ```dart class MyDio with DioMixin implements Dio { // ... } ``` -------------------------------- ### Apache License 2.0 Source: https://pub.dev/packages/dio_http_cache Standard Apache License 2.0 text for the package. ```text Copyright 2019 Hurshi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Import the library Source: https://pub.dev/packages/diox/install Include this import statement in your Dart files to access the diox API. ```dart import 'package:diox/diox.dart'; ``` -------------------------------- ### Import the library Source: https://pub.dev/packages/dio_cache_interceptor/install Include this statement in your Dart files to access the package functionality. ```dart import 'package:dio_cache_interceptor/dio_cache_interceptor.dart'; ``` -------------------------------- ### Configure Proxy for IOHttpClientAdapter Source: https://pub.dev/packages/diox Uses the onHttpClientCreate callback to route requests through a specific proxy server. ```dart void initAdapter() { dio.httpClientAdapter = IOHttpClientAdapter()..onHttpClientCreate = (client) { // Config the client. client.findProxy = (uri) { // Forward all request to proxy "localhost:8888". return 'PROXY localhost:8888'; }; // You can also create a new HttpClient for Dio instead of returning, // but a client must being returned here. return client; }; } ``` -------------------------------- ### Add dio dependency via command line Source: https://pub.dev/packages/dio/install Use these commands to automatically add the latest version of dio to your project dependencies. ```bash $ dart pub add dio ``` ```bash $ flutter pub add dio ``` -------------------------------- ### Basic Usage of CookieManager Source: https://pub.dev/packages/diox_cookie_manager Initialize a CookieJar and add the CookieManager interceptor to your Diox instance. ```dart import 'package:cookie_jar/cookie_jar.dart'; import 'package:diox/diox.dart'; import 'package:diox_cookie_manager/diox_cookie_manager.dart'; void main() async { final dio = Dio(); final cookieJar = CookieJar(); dio.interceptors.add(CookieManager(cookieJar)); // First request, and save cookies (CookieManager do it). await dio.get("https://dart.dev"); // Print cookies print(await cookieJar.loadForRequest(Uri.parse("https://dart.dev"))); // Second request with the cookies await dio.get('https://dart.dev'); } ``` -------------------------------- ### Configure Platform-Specific HttpClientAdapters Source: https://pub.dev/packages/dio Explicitly set the adapter for Web or native platforms using specific imports. ```dart import 'package:dio/browser.dart'; // ... dio.httpClientAdapter = BrowserHttpClientAdapter(); ``` ```dart import 'package:dio/io.dart'; // ... dio.httpClientAdapter = IOHttpClientAdapter(); ``` -------------------------------- ### Configure RetryInterceptor with Dio Source: https://pub.dev/packages/dio_smart_retry/example Initializes the Dio client and adds the RetryInterceptor with custom retry counts and delay intervals. ```dart import 'dart:async'; import 'package:dio/dio.dart'; import 'package:dio_smart_retry/dio_smart_retry.dart'; Future main() async { final dio = Dio(); // Add the interceptor dio.interceptors.add( RetryInterceptor( dio: dio, logPrint: print, // specify log function (optional) retries: 4, // retry count (optional) retryDelays: const [ // set delays between retries (optional) Duration(seconds: 1), // wait 1 sec before the first retry Duration(seconds: 2), // wait 2 sec before the second retry Duration(seconds: 3), // wait 3 sec before the third retry Duration(seconds: 4), // wait 4 sec before the fourth retry ], ), ); /// Sending a failing request for 4 times from 1s to 4s await dio.get('https://mock.codes/500'); } ``` -------------------------------- ### Using application/x-www-form-urlencoded Source: https://pub.dev/packages/dio/versions/5.10.0 Explains how to send request data using the application/x-www-form-urlencoded format instead of the default JSON serialization. ```APIDOC ## Using application/x-www-form-urlencoded ### Description By default, Dio serializes data to JSON. You can override this to use application/x-www-form-urlencoded either globally or per request. ### Example ```dart // Per request example dio.post( '/info', data: {'id': 5}, options: Options(contentType: Headers.formUrlEncodedContentType), ); ``` ``` -------------------------------- ### Configure application/x-www-form-urlencoded format Source: https://pub.dev/packages/diox Set the content type to form-urlencoded at the instance level or for a single request. ```dart // Instance level dio.options.contentType = Headers.formUrlEncodedContentType; // or only works once dio.post( '/info', data: {'id': 5}, options: Options(contentType: Headers.formUrlEncodedContentType), ); ``` -------------------------------- ### Import Platform-Specific Classes Source: https://pub.dev/packages/diox/changelog Use these import paths to access platform-specific classes for IO or browser environments. ```dart import 'package:diox/io.dart'; ``` ```dart import 'package:diox/browser.dart'; ``` -------------------------------- ### Import the package Source: https://pub.dev/packages/dio_cache_interceptor_db_store/install Include this import statement in your Dart files to access the library functionality. ```dart import 'package:dio_cache_interceptor_db_store/dio_cache_interceptor_db_store.dart'; ``` -------------------------------- ### Import the package Source: https://pub.dev/packages/dio_cache_interceptor_file_store/install Include this import statement in your Dart files to access the library functionality. ```dart import 'package:dio_cache_interceptor_file_store/dio_cache_interceptor_file_store.dart'; ``` -------------------------------- ### Configure Dio with CookieManager Source: https://pub.dev/packages/diox_cookie_manager/example Demonstrates how to add the CookieManager interceptor to a Dio instance and perform requests with cookie persistence. ```dart import 'package:cookie_jar/cookie_jar.dart'; import 'package:diox/diox.dart'; import 'package:diox_cookie_manager/diox_cookie_manager.dart'; void main() async { final dio = Dio(); final cookieJar = CookieJar(); dio.interceptors.add(CookieManager(cookieJar)); await dio.get('https://baidu.com/'); // Print cookies print(cookieJar.loadForRequest(Uri.parse('https://baidu.com/'))); // second request with the cookie await dio.get('https://baidu.com/'); } ``` -------------------------------- ### Implement Dio Image Provider Source: https://pub.dev/packages/dio_cache_interceptor/example Custom ImageProvider to load images using the Dio client. Note that production implementations should use streams to avoid OOM issues. ```dart class _ImageCacheTab extends StatefulWidget { const _ImageCacheTab(this.caller); final Caller caller; @override _ImageCacheTabState createState() => _ImageCacheTabState(); } class _ImageCacheTabState extends State<_ImageCacheTab> { final url = 'https://fr.wikipedia.org/static/images/mobile/copyright/wikipedia.png'; @override Widget build(BuildContext context) { return SafeArea( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const Text( 'Look at print output to get status code', textAlign: TextAlign.center, ), Image(image: DioImageProvider(url, widget.caller)), ], ), ), ); } } /// Basic image downloader /// Production implementation should use stream instead /// to avoid OOM problems & improve performance class DioImageProvider extends ImageProvider { final String url; final Caller caller; const DioImageProvider(this.url, this.caller); @override ImageStreamCompleter loadImage( DioImageProvider key, ImageDecoderCallback decode, ) { return MultiFrameImageStreamCompleter( codec: _loadAsync(decode), scale: 1.0, ); } ``` -------------------------------- ### Upload Multiple Files Source: https://pub.dev/packages/dio/versions/5.10.0 Demonstrates two methods for adding multiple files to FormData, including handling array keys. ```dart final formData = FormData.fromMap({ 'files': [ MultipartFile.fromFileSync('path/to/upload1.txt', filename: 'upload1.txt'), MultipartFile.fromFileSync('path/to/upload2.txt', filename: 'upload2.txt'), ], }); ``` ```dart final formData = FormData(); formData.files.addAll([ MapEntry( 'files', MultipartFile.fromFileSync('./example/upload.txt',filename: 'upload.txt'), ), MapEntry( 'files', MultipartFile.fromFileSync('./example/upload.txt',filename: 'upload.txt'), ), ]); ``` -------------------------------- ### Implement _loadAsync for DioImageProvider Source: https://pub.dev/packages/dio_cache_interceptor/example Fetches image bytes using Dio and decodes them into an ImageDecoderCallback. Requires handling of null or empty response data. ```dart Future _loadAsync(ImageDecoderCallback decode) async { final response = await caller.dio.get( url, options: Options(responseType: ResponseType.bytes), ); final bytes = response.data; if (bytes == null || bytes.isEmpty) { throw StateError('$url cannot be loaded as an image.'); } if (kDebugMode) { print( response.statusCode == 200 ? 'From network ${response.statusCode}' : 'From cache ${response.statusCode}', ); } return decode(await ImmutableBuffer.fromUint8List(bytes)); } ``` -------------------------------- ### Download a file Source: https://pub.dev/packages/diox Downloads a file from a URL to a local path. ```dart response = await dio.download( 'https://pub.dev/', (await getTemporaryDirectory()).path + 'pub.html', ); ``` -------------------------------- ### Configure a proxy Source: https://pub.dev/packages/dio_http2_adapter Set a proxy URI within the ConnectionManager configuration. ```dart void main() async { final dio = Dio() ..options.baseUrl = 'https://pub.dev' ..interceptors.add(LogInterceptor()) ..httpClientAdapter = Http2Adapter( ConnectionManager( idleTimeout: Duration(seconds: 10), onClientCreate: (_, config) => config.proxy = Uri.parse('http://login:password@192.168.0.1:8888'), ), ); } ``` -------------------------------- ### Handling DioException Source: https://pub.dev/packages/dio/versions/5.10.0 Demonstrates how to catch and handle DioException when a request fails, including accessing response data or request options. ```APIDOC ## Handling DioException ### Description When a request fails, Dio throws a DioException. This snippet shows how to catch the exception and inspect the response or request options. ### Usage ```dart try { await dio.get('https://api.pub.dev/not-exist'); } on DioException catch (e) { if (e.response != null) { print(e.response.data); } else { print(e.message); } } ``` ``` -------------------------------- ### Request Options configuration Source: https://pub.dev/packages/diox Defines the structure and fields available for configuring HTTP requests. ```dart /// Http method. String method; /// Request base url, it can contain sub path, like: https://dart.dev/api/. String? baseUrl; /// Http request headers. Map? headers; /// Timeout for opening url. Duration? connectTimeout; /// Whenever more than [receiveTimeout] passes between two events from response stream, /// [Dio] will throw the [DioError] with [DioErrorType.RECEIVE_TIMEOUT]. /// Note: This is not the receiving time limitation. Duration? receiveTimeout; /// Request data, can be any type. dynamic data; /// If the `path` starts with 'http(s)', the `baseURL` will be ignored, otherwise, /// it will be combined and then resolved with the baseUrl. String path; /// The request Content-Type. /// If you want to encode request body with 'application/x-www-form-urlencoded', /// you can set [Headers.formUrlEncodedContentType], and [Dio] /// will automatically encode the request body. String? contentType; /// [responseType] indicates the type of data that the server will respond with /// options which defined in [ResponseType] are `json`, `stream`, `plain`. /// /// The default value is `json`, dio will parse response string to json object automatically /// when the content-type of response is 'application/json'. /// /// If you want to receive response data with binary bytes, for example, /// downloading a image, use `stream`. /// /// If you want to receive the response data with String, use `plain`. ResponseType? responseType; /// `validateStatus` defines whether the request is successful for a given /// HTTP response status code. If `validateStatus` returns `true` , /// the request will be perceived as successful; otherwise, considered as failed. ValidateStatus? validateStatus; /// Custom field that you can retrieve it later in /// [Interceptor], [Transformer] and the [Response] object. Map? extra; /// Common query parameters. Map*/ >? queryParameters; /// [listFormat] indicates the format of collection data in request options。 /// The default value is `multiCompatible` ListFormat? listFormat; ``` -------------------------------- ### Advanced Cache Configuration Options Source: https://pub.dev/packages/dio_http_cache Various configurations for cache keys, stale times, and refresh behavior. ```dart buildCacheOptions(Duration(days: 7), subKey: "page=1") ``` ```dart buildCacheOptions(Duration(days: 7), maxStale: Duration(days: 10)) ``` ```dart buildCacheOptions(Duration(days: 7), forceRefresh: true) ``` -------------------------------- ### Options Class Source: https://pub.dev/packages/dio The Options class defines the configuration for a single HTTP request in Dio. ```APIDOC ## Options Class ### Description Configuration object for a single HTTP request in Dio. These settings are merged with BaseOptions when making a request. ### Properties - **method** (String) - The HTTP request method. - **sendTimeout** (Duration?) - Timeout when sending data. - **receiveTimeout** (Duration?) - Timeout when receiving data. - **transformTimeout** (Duration?) - Timeout when transforming response data. - **extra** (Map?) - Custom fields for use in Interceptors or Transformers. - **headers** (Map?) - HTTP request headers. - **preserveHeaderCase** (bool?) - Whether to preserve the case of header keys. - **responseType** (ResponseType?) - The expected format of the response (json, plain, bytes, stream). - **contentType** (String?) - The request content-type. - **validateStatus** (ValidateStatus?) - Callback to determine if a status code is considered successful. - **receiveDataWhenStatusError** (bool?) - Whether to retrieve data if the status code indicates a failure. - **followRedirects** (bool?) - Whether to follow HTTP redirects. - **maxRedirects** (int?) - Maximum number of redirects allowed. - **persistentConnection** (bool?) - Whether to use persistent connections. - **requestEncoder** (RequestEncoder?) - Custom encoder for request data. - **responseDecoder** (ResponseDecoder?) - Custom decoder for response data. - **listFormat** (ListFormat?) - Format of collection data in query parameters and x-www-url-encoded bodies. ``` -------------------------------- ### Import diox_flutter_transformer Source: https://pub.dev/packages/diox_flutter_transformer Include the necessary imports in your Dart file. ```dart import 'package:dio/dio.dart'; import 'package:diox_flutter_transformer/diox_flutter_transformer.dart'; ``` -------------------------------- ### Handle response as bytes Source: https://pub.dev/packages/diox Configures the request to return the response body as a list of bytes. ```dart final rs = await Dio().get>( url, options: Options(responseType: ResponseType.bytes), // Set the response type to `bytes`. ); print(rs.data); // Type: List. ``` -------------------------------- ### Configure Dependency Overrides Source: https://pub.dev/packages/diox Use this configuration to override the standard dio package with the Diox fork. ```yaml dependency_overrides: dio: git: url: https://github.com/cfug/diox path: dio/ ref: dio ``` -------------------------------- ### Initialize DioInterceptToCurl Source: https://pub.dev/packages/dio_intercept_to_curl Add the interceptor to your Dio instance to begin logging requests as curl commands. ```dart _dio = Dio(); _dio.interceptors.add(DioInterceptToCurl()); ```