gsd_restapi 0.1.9 copy "gsd_restapi: ^0.1.9" to clipboard
gsd_restapi: ^0.1.9 copied to clipboard

This package provides comprehensive REST API functionality for Flutter applications.

example/lib/main.dart

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GSD RestAPI Example',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const RestApiExample(),
    );
  }
}

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

  @override
  State<RestApiExample> createState() => _RestApiExampleState();
}

class _RestApiExampleState extends State<RestApiExample> {
  late RestApiDOCUframeManager apiManager;
  String _status = 'Not connected';
  String _sessionId = 'None';
  bool _isLoggedIn = false;
  final List<String> _logs = [];

  @override
  void initState() {
    super.initState();
    _initializeApiManager();
  }

  void _initializeApiManager() {
    // Initialize the REST API Manager
    apiManager = RestApiDOCUframeManager(
      'GSD-App', // App Key
      'GSDAdmin', // Username
      ['GSD-RestApi', 'GSD-App'], // App Names
      'https://demo.example.com', // Server URL (replace with your server)
      'demo', // Database Alias
      device: RestApiDevice("123"),
      allowSslError: true, // For demo purposes - set to false in production
    );

    // Subscribe to events
    apiManager.sessionIdChangedEvent.subscribe((args) {
      setState(() {
        _sessionId = apiManager.sessionId ?? 'None';
        _addLog('Session ID changed: $_sessionId');
      });
    });

    apiManager.userAndPassWrongEvent.subscribe((args) {
      setState(() {
        _addLog('Authentication failed: Wrong username or password');
      });
    });

    apiManager.licenseWrongEvent.subscribe((args) {
      setState(() {
        _addLog('License error detected');
      });
    });
  }

  void _addLog(String message) {
    _logs.add('${DateTime.now().toLocal()}: $message');
    if (_logs.length > 20) {
      _logs.removeAt(0);
    }
  }

  Future<void> _checkService() async {
    try {
      setState(() {
        _status = 'Checking service...';
      });

      RestApiCheckServiceResponse response = await apiManager.checkService();

      setState(() {
        _status = response.isOk ? 'Service available' : 'Service unavailable';
        _addLog('Service check: ${response.isOk ? 'OK' : 'Failed'}');
      });
    } catch (e) {
      setState(() {
        _status = 'Service check failed';
        _addLog('Service check error: $e');
      });
    }
  }

  Future<void> _login() async {
    try {
      setState(() {
        _status = 'Logging in...';
      });

      // In a real app, you would get this from user input
      // This is a demo password hash (MD5 of "demo")
      String passwordHash = 'fe01ce2a7fbac8fafaed7c982a04e229';

      apiManager.setPassword(passwordHash);
      RestApiLoginResponse loginResponse = await apiManager.login(passwordHash);

      setState(() {
        _isLoggedIn = loginResponse.isOk;
        _status = _isLoggedIn ? 'Logged in successfully' : 'Login failed';
        _sessionId = apiManager.sessionId ?? 'None';
        _addLog('Login attempt: ${_isLoggedIn ? 'Success' : 'Failed'}');
      });
    } catch (e) {
      setState(() {
        _status = 'Login error';
        _isLoggedIn = false;
        _addLog('Login error: $e');
      });
    }
  }

  Future<void> _checkSession() async {
    try {
      setState(() {
        _status = 'Checking session...';
      });

      RestApiResponse sessionResponse = await apiManager.checkSession();

      setState(() {
        _status = sessionResponse.isOk ? 'Session valid' : 'Session invalid';
        _addLog('Session check: ${sessionResponse.isOk ? 'Valid' : 'Invalid'}');
      });
    } catch (e) {
      setState(() {
        _status = 'Session check failed';
        _addLog('Session check error: $e');
      });
    }
  }

  Future<void> _logout() async {
    try {
      setState(() {
        _status = 'Logging out...';
      });

      await apiManager.logout();

      setState(() {
        _isLoggedIn = false;
        _sessionId = 'None';
        _status = 'Logged out';
        _addLog('Logged out successfully');
      });
    } catch (e) {
      setState(() {
        _status = 'Logout error';
        _addLog('Logout error: $e');
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GSD RestAPI Example'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Connection Status',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Text('Status: $_status'),
                    Text('Session ID: $_sessionId'),
                    Text('Logged in: ${_isLoggedIn ? 'Yes' : 'No'}'),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Actions',
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    const SizedBox(height: 8),
                    Wrap(
                      spacing: 8,
                      children: [
                        ElevatedButton(
                          onPressed: _checkService,
                          child: const Text('Check Service'),
                        ),
                        ElevatedButton(
                          onPressed: _login,
                          child: const Text('Login'),
                        ),
                        ElevatedButton(
                          onPressed: _isLoggedIn ? _checkSession : null,
                          child: const Text('Check Session'),
                        ),
                        ElevatedButton(
                          onPressed: _isLoggedIn ? _logout : null,
                          child: const Text('Logout'),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: Card(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Activity Log',
                        style: Theme.of(context).textTheme.headlineSmall,
                      ),
                      const SizedBox(height: 8),
                      Expanded(
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.grey[100],
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: ListView.builder(
                            itemCount: _logs.length,
                            itemBuilder: (context, index) {
                              return Text(
                                _logs[index],
                                style: const TextStyle(
                                  fontFamily: 'monospace',
                                  fontSize: 12,
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // Clean up subscriptions
    apiManager.sessionIdChangedEvent.unsubscribeAll();
    apiManager.userAndPassWrongEvent.unsubscribeAll();
    apiManager.licenseWrongEvent.unsubscribeAll();
    super.dispose();
  }
}