Skip to main content

high_q_dio 0.0.1 copy "high_q_dio: ^0.0.1" to clipboard
high_q_dio: ^0.0.1 copied to clipboard

discontinued

A production-ready Dio client wrapper for Flutter featuring TanStack-style Query caching, secure concurrent token refresh, automatic retries, and resumable chunked uploader.

example/lib/main.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:high_q_dio/high_q_dio.dart' hide State;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HighQ Dio Premium Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.teal,
          brightness: Brightness.light,
        ),
        useMaterial3: true,
      ),
      home: const DemoScreen(),
    );
  }
}

class DemoScreen extends StatefulWidget {
  const DemoScreen({super.key});

  @override
  State<DemoScreen> createState() => _DemoScreenState();
}

class _DemoScreenState extends State<DemoScreen> {
  late final ApiClient _apiClient;
  late final TokenManager _tokenManager;
  late final CancellationManager _cancellationManager;
  final _mockInterceptor = MockInterceptor();

  // Log of events to show in UI console
  final List<String> _consoleLogs = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _log('Initializing HighQ Dio Client...');

    final dio = Dio(BaseOptions(
      baseUrl: 'https://jsonplaceholder.typicode.com',
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    ));

    // Add Mock Interceptor for simulations (401 Refresh & Delays)
    dio.interceptors.add(_mockInterceptor);

    _tokenManager = TokenManager(
      initialTokenStore: const TokenStore(
        accessToken: 'initial_jwt_token_123',
        refreshToken: 'initial_refresh_token_456',
      ),
      onPersist: (store) async {
        _log('Tokens Persisted: access=${store.accessToken?.substring(0, 10)}...');
      },
    );

    _cancellationManager = CancellationManager();

    final refreshInterceptor = DioRefreshInterceptor(
      dio: dio,
      config: DioRefreshConfig(
        tokenManager: _tokenManager,
        authHeaderProvider: const BearerAuthHeaderProvider(),
        onRefresh: (client, store, cancelToken) async {
          _log('🔄 Refreshing Access Token in background...');
          await Future.delayed(const Duration(seconds: 1)); // simulate request
          return const TokenStore(
            accessToken: 'refreshed_jwt_token_789',
            refreshToken: 'refreshed_refresh_token_000',
          );
        },
        shouldRefresh: (response) => response?.statusCode == 401,
      ),
    );

    _apiClient = ApiClient(
      client: dio,
      refreshInterceptor: refreshInterceptor,
      cacheEngine: LRUCacheEngine(maxEntries: 10),
      deduplicator: RequestDeduplicator(),
      cancellationManager: _cancellationManager,
      languageProvider: () => 'ar', // Arabic header demo
    );
    _log('HighQ Dio Client ready!');
  }

  void _log(String message) {
    setState(() {
      _consoleLogs.insert(0, '[${DateTime.now().toString().substring(11, 19)}] $message');
    });
  }

  Future<void> _executeGet(CacheStrategy strategy) async {
    setState(() => _isLoading = true);
    _log('Executing GET request (CacheStrategy: ${strategy.name})...');

    final result = await _apiClient.get<Map<String, dynamic>>(
      endPoint: '/posts/1',
      parser: (json) async => Map<String, dynamic>.from(json),
      config: RequestConfig(
        cacheStrategy: strategy,
        cacheDuration: const Duration(seconds: 30),
        staleDuration: const Duration(seconds: 10),
        tags: const ['post-1'],
      ),
    );

    result.fold(
      (failure) => _log('❌ GET Request Failed: ${failure.message}'),
      (data) => _log('✅ GET Success! Title: "${data['title']}"'),
    );
    setState(() => _isLoading = false);
  }

  Future<void> _executePost() async {
    setState(() => _isLoading = true);
    _log('Executing POST request (Invalidates tag "post-1")...');

    final result = await _apiClient.post<Map<String, dynamic>>(
      endPoint: '/posts',
      parser: (json) async => Map<String, dynamic>.from(json),
      config: const RequestConfig(
        body: {'title': 'New Post Title', 'body': 'New Post Content', 'userId': 1},
        invalidateTagsOnSuccess: ['post-1'], // Automate cache invalidation
      ),
    );

    result.fold(
      (failure) => _log('❌ POST Request Failed: ${failure.message}'),
      (data) {
        _log('✅ POST Success! New Post Created (ID: ${data['id']})');
        _log('â„šī¸ Automatically invalidated cache for tag "post-1"');
      },
    );
    setState(() => _isLoading = false);
  }

  Future<void> _executeRefreshSimulation() async {
    setState(() => _isLoading = true);
    _log('Simulating a request that gets a 401 response...');
    _mockInterceptor.reset401();

    final result = await _apiClient.get<Map<String, dynamic>>(
      endPoint: '/mock-401',
      parser: (json) async => Map<String, dynamic>.from(json),
    );

    result.fold(
      (failure) => _log('❌ Request Failed: ${failure.message}'),
      (data) => _log('✅ Request succeeded after transparent refresh! Message: ${data['data']}'),
    );
    setState(() => _isLoading = false);
  }

  CancelToken? _currentCancelToken;

  Future<void> _executeCancelSimulation() async {
    setState(() => _isLoading = true);
    _log('Starting delayed request (3 seconds)...');

    final cancelToken = CancelToken();
    _currentCancelToken = cancelToken;

    final result = await _apiClient.get<Map<String, dynamic>>(
      endPoint: '/mock-delay',
      parser: (json) async => Map<String, dynamic>.from(json),
      config: RequestConfig(
        cancelToken: cancelToken,
      ),
    );

    result.fold(
      (failure) => _log('❌ Request Status: ${failure.message}'),
      (data) => _log('✅ Completed request: ${data['message']}'),
    );

    _currentCancelToken = null;
    setState(() => _isLoading = false);
  }

  void _cancelRequest() {
    if (_currentCancelToken != null) {
      _log('⛔ Request Cancellation requested...');
      _currentCancelToken!.cancel('User cancelled the request');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('HighQ Dio Client Dashboard', style: TextStyle(fontWeight: FontWeight.bold)),
        centerTitle: true,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
      ),
      body: Column(
        children: [
          // Control Actions Panel
          Expanded(
            flex: 3,
            child: GridView.count(
              crossAxisCount: 2,
              padding: const EdgeInsets.all(16),
              crossAxisSpacing: 16,
              mainAxisSpacing: 16,
              childAspectRatio: 1.6,
              children: [
                _buildCard(
                  title: 'GET Request',
                  subtitle: 'Select Caching Policy',
                  color: Colors.blue.shade50,
                  icon: Icons.download_rounded,
                  actions: [
                    ElevatedButton(
                      onPressed: _isLoading ? null : () => _executeGet(CacheStrategy.networkOnly),
                      child: const Text('Network Only'),
                    ),
                    ElevatedButton(
                      onPressed: _isLoading ? null : () => _executeGet(CacheStrategy.cacheFirst),
                      child: const Text('Cache First'),
                    ),
                  ],
                ),
                _buildCard(
                  title: 'POST Request',
                  subtitle: 'Mutate & Invalidate Tag',
                  color: Colors.green.shade50,
                  icon: Icons.upload_rounded,
                  actions: [
                    ElevatedButton(
                      onPressed: _isLoading ? null : _executePost,
                      child: const Text('Send & Invalidate'),
                    ),
                  ],
                ),
                _buildCard(
                  title: '401 Refresh Interceptor',
                  subtitle: 'Simulate Auth Expired',
                  color: Colors.orange.shade50,
                  icon: Icons.autorenew_rounded,
                  actions: [
                    ElevatedButton(
                      onPressed: _isLoading ? null : _executeRefreshSimulation,
                      child: const Text('Simulate 401'),
                    ),
                  ],
                ),
                _buildCard(
                  title: 'Request Cancellation',
                  subtitle: 'Delay & Cancel Fetch',
                  color: Colors.red.shade50,
                  icon: Icons.cancel_schedule_send_rounded,
                  actions: [
                    ElevatedButton(
                      onPressed: _isLoading ? null : _executeCancelSimulation,
                      child: const Text('Start 3s Fetch'),
                    ),
                    ElevatedButton(
                      onPressed: _currentCancelToken == null ? null : _cancelRequest,
                      style: ElevatedButton.styleFrom(backgroundColor: Colors.red.shade100),
                      child: const Text('Cancel Fetch', style: TextStyle(color: Colors.red)),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // Console Logs output
          Expanded(
            flex: 2,
            child: Container(
              margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey.shade900,
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: Colors.grey.shade800),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        'Console log output',
                        style: TextStyle(color: Colors.grey, fontWeight: FontWeight.bold),
                      ),
                      TextButton.icon(
                        onPressed: () => setState(() => _consoleLogs.clear()),
                        icon: const Icon(Icons.delete_outline, size: 16, color: Colors.grey),
                        label: const Text('Clear', style: TextStyle(color: Colors.grey, fontSize: 12)),
                      ),
                    ],
                  ),
                  const Divider(color: Colors.grey, height: 1),
                  Expanded(
                    child: ListView.builder(
                      itemCount: _consoleLogs.length,
                      itemBuilder: (context, index) {
                        return Padding(
                          padding: const EdgeInsets.symmetric(vertical: 4.0),
                          child: Text(
                            _consoleLogs[index],
                            style: const TextStyle(
                              fontFamily: 'Courier',
                              color: Colors.greenAccent,
                              fontSize: 13,
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCard({
    required String title,
    required String subtitle,
    required Color color,
    required IconData icon,
    required List<Widget> actions,
  }) {
    return Card(
      elevation: 2,
      color: color,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              children: [
                Icon(icon, size: 24, color: Colors.teal.shade800),
                const SizedBox(width: 8),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14)),
                      Text(subtitle, style: const TextStyle(color: Colors.grey, fontSize: 11)),
                    ],
                  ),
                ),
              ],
            ),
            const Spacer(),
            Wrap(
              spacing: 8,
              runSpacing: 4,
              children: actions,
            ),
          ],
        ),
      ),
    );
  }
}

// Custom Interceptor to mock custom behaviors (401 Refresh & Delays) without real server configs
class MockInterceptor extends Interceptor {
  bool _shouldFail = true;

  void reset401() {
    _shouldFail = true;
  }

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    if (options.path.contains('/mock-401')) {
      if (_shouldFail) {
        _shouldFail = false;
        handler.reject(DioException(
          requestOptions: options,
          response: Response(
            requestOptions: options,
            statusCode: 401,
            data: {'message': 'Unauthorized: JWT Token Expired'},
          ),
          type: DioExceptionType.badResponse,
        ));
        return;
      } else {
        handler.resolve(Response(
          requestOptions: options,
          statusCode: 200,
          data: {'status': 'ok', 'data': 'Authenticated successfully!'},
        ));
        return;
      }
    }

    if (options.path.contains('/mock-delay')) {
      Future.delayed(const Duration(seconds: 3)).then((_) {
        if (options.cancelToken != null && options.cancelToken!.isCancelled) {
          return;
        }
        handler.resolve(Response(
          requestOptions: options,
          statusCode: 200,
          data: {'message': 'Completed delayed request successfully!'},
        ));
      });
      return;
    }

    super.onRequest(options, handler);
  }
}
0
likes
130
points
12
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A production-ready Dio client wrapper for Flutter featuring TanStack-style Query caching, secure concurrent token refresh, automatic retries, and resumable chunked uploader.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

collection, crypto, dartz, dio, dio_cache_interceptor, equatable, flutter, high_q_dio_logger, http_parser, mime, path, uuid

More

Packages that depend on high_q_dio