gt_api 1.0.0 copy "gt_api: ^1.0.0" to clipboard
gt_api: ^1.0.0 copied to clipboard

A production-ready Flutter API service package with Dio-based HTTP operations, automatic retry, comprehensive logging, file downloads, and network checking.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:gt_api/gt_api.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // Configure API using initialize method
  ApiConfig().initialize(
    baseUrl: 'https://jsonplaceholder.typicode.com',
    enableLogs: true,
    enableRetry: true,
  );

  // Initialize API Service
  ApiService().initialize();

  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GT API Example',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const ApiExampleScreen(),
    );
  }
}

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

  @override
  State<ApiExampleScreen> createState() => _ApiExampleScreenState();
}

class _ApiExampleScreenState extends State<ApiExampleScreen> {
  final ApiService _api = ApiService();
  String _result = 'Tap a button to make an API call';
  bool _isLoading = false;

  Future<void> _fetchUsers() async {
    setState(() => _isLoading = true);

    final response = await _api.get('/users');

    setState(() {
      _isLoading = false;
      if (response.isSuccess) {
        final users = response.raw as List;
        _result =
            'Fetched ${users.length} users!\n\n'
            'First user: ${users.first['name']}';
      } else {
        _result = 'Error: ${response.error?.message}';
      }
    });
  }

  Future<void> _fetchSinglePost() async {
    setState(() => _isLoading = true);

    final response = await _api.get('/posts/1');

    setState(() {
      _isLoading = false;
      if (response.isSuccess) {
        final post = response.raw as Map<String, dynamic>;
        _result =
            'Post Title:\n${post['title']}\n\n'
            'Body:\n${post['body']}';
      } else {
        _result = 'Error: ${response.error?.message}';
      }
    });
  }

  Future<void> _createPost() async {
    setState(() => _isLoading = true);

    final response = await _api.post(
      '/posts',
      data: {
        'title': 'My New Post',
        'body': 'This is the content of my post.',
        'userId': 1,
      },
    );

    setState(() {
      _isLoading = false;
      if (response.isSuccess) {
        final post = response.raw as Map<String, dynamic>;
        _result =
            'Created Post!\n\n'
            'ID: ${post['id']}\n'
            'Title: ${post['title']}';
      } else {
        _result = 'Error: ${response.error?.message}';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GT API Example'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Result Card
            Expanded(
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: _isLoading
                      ? const Center(child: CircularProgressIndicator())
                      : SingleChildScrollView(child: Text(_result)),
                ),
              ),
            ),
            const SizedBox(height: 16),

            // Action Buttons
            Text('API Calls', style: Theme.of(context).textTheme.titleLarge),
            const SizedBox(height: 12),

            ElevatedButton.icon(
              onPressed: _isLoading ? null : _fetchUsers,
              icon: const Icon(Icons.people),
              label: const Text('GET /users'),
            ),
            const SizedBox(height: 8),

            ElevatedButton.icon(
              onPressed: _isLoading ? null : _fetchSinglePost,
              icon: const Icon(Icons.article),
              label: const Text('GET /posts/1'),
            ),
            const SizedBox(height: 8),

            ElevatedButton.icon(
              onPressed: _isLoading ? null : _createPost,
              icon: const Icon(Icons.add),
              label: const Text('POST /posts'),
            ),
          ],
        ),
      ),
    );
  }
}
0
likes
160
points
139
downloads

Publisher

unverified uploader

Weekly Downloads

A production-ready Flutter API service package with Dio-based HTTP operations, automatic retry, comprehensive logging, file downloads, and network checking.

Repository (GitHub)
View/report issues

Topics

#api #dio #http #network #rest

Documentation

API reference

License

MIT (license)

Dependencies

connectivity_plus, dio, flutter, path_provider

More

Packages that depend on gt_api