offline_sync_queue 0.0.2 copy "offline_sync_queue: ^0.0.2" to clipboard
offline_sync_queue: ^0.0.2 copied to clipboard

The ultimate offline-first engine for Flutter. Automatically queue actions/jobs while offline and sync them when connection is restored.

example/lib/main.dart

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Offline Sync Queue Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.teal,
          brightness: Brightness.dark,
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Offline Sync Queue'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _controller = TextEditingController();
  final List<String> _activityLogs = [];
  final OfflineSyncQueue _syncQueue = OfflineSyncQueue();

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

  void _setupSyncQueue() {
    _syncQueue.startSync((Map<String, dynamic> job) async {
      // Simulate API sync delay
      await Future.delayed(const Duration(seconds: 1));

      final text = job['text'] as String?;
      final timestamp = job['timestamp'] as String?;

      // Log the synced action
      setState(() {
        _activityLogs.add(
          "Synced successfully: '$text' (queued at $timestamp)",
        );
      });

      // Show snackbar notifying the user the job was synced
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text("Job synced: $text"),
            backgroundColor: Colors.teal,
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
      return true;
    });
  }

  Future<void> _handleSubmit(bool isOnline) async {
    final text = _controller.text.trim();
    if (text.isEmpty) return;

    final timestamp = DateTime.now().toIso8601String().substring(11, 19);
    final jobData = {'text': text, 'timestamp': timestamp};

    if (!isOnline) {
      // Offline: Add to queue
      await _syncQueue.addJob(jobData);
      setState(() {
        _activityLogs.add("Queued locally (offline): '$text' at $timestamp");
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text("Device offline. Queued locally: '$text'"),
            backgroundColor: Colors.orange,
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    } else {
      // Online: Process immediately
      setState(() {
        _activityLogs.add(
          "Processed immediately (online): '$text' at $timestamp",
        );
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text("Sent immediately: '$text'"),
            backgroundColor: Colors.green,
            behavior: SnackBarBehavior.floating,
          ),
        );
      }
    }
    _controller.clear();
  }

  @override
  void dispose() {
    _controller.dispose();
    _syncQueue.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<bool>(
      stream: _syncQueue.isOnlineStream,
      initialData: _syncQueue.isOnline,
      builder: (context, snapshot) {
        final isOnline = snapshot.data ?? false;
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
            actions: [
              Padding(
                padding: const EdgeInsets.only(right: 16.0),
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 6,
                  ),
                  decoration: BoxDecoration(
                    color: isOnline
                        ? Colors.green.shade800
                        : Colors.red.shade800,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        isOnline ? Icons.wifi : Icons.wifi_off,
                        size: 14,
                        color: Colors.white,
                      ),
                      const SizedBox(width: 6),
                      Text(
                        isOnline ? 'Online' : 'Offline',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          body: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Card(
                  elevation: 4,
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        const Text(
                          'Submit action',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 8),
                        TextField(
                          controller: _controller,
                          decoration: const InputDecoration(
                            labelText: 'Enter text/job data',
                            border: OutlineInputBorder(),
                          ),
                        ),
                        const SizedBox(height: 12),
                        ElevatedButton(
                          onPressed: () => _handleSubmit(isOnline),
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(vertical: 16),
                          ),
                          child: const Text('Submit Job'),
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 20),

                // Show reactive local queue items
                StreamBuilder<List<Map<String, dynamic>>>(
                  stream: _syncQueue.queueStream,
                  builder: (context, queueSnapshot) {
                    final queue = queueSnapshot.data ?? [];
                    if (queue.isEmpty) return const SizedBox.shrink();
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Pending Sync Queue (${queue.length}):',
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.orange,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Card(
                          color: Colors.orange.withAlpha(26),
                          shape: const RoundedRectangleBorder(
                            side: BorderSide(color: Colors.orange, width: 0.5),
                            borderRadius: BorderRadius.all(Radius.circular(12)),
                          ),
                          child: Column(
                            children: queue.map((job) {
                              return ListTile(
                                leading: const Icon(
                                  Icons.sync_problem,
                                  color: Colors.orange,
                                ),
                                title: Text(job['text'] ?? ''),
                                subtitle: Text(
                                  "Queued at: ${job['timestamp'] ?? ''}",
                                ),
                              );
                            }).toList(),
                          ),
                        ),
                        const SizedBox(height: 16),
                      ],
                    );
                  },
                ),

                const Text(
                  'Activity Log:',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                Expanded(
                  child: Card(
                    child: _activityLogs.isEmpty
                        ? const Center(
                            child: Text(
                              'No activity logs yet.',
                              style: TextStyle(color: Colors.grey),
                            ),
                          )
                        : ListView.builder(
                            itemCount: _activityLogs.length,
                            itemBuilder: (context, index) {
                              final log = _activityLogs[index];
                              IconData logIcon = Icons.send;
                              Color iconColor = Colors.green;
                              if (log.contains("Synced")) {
                                logIcon = Icons.sync;
                                iconColor = Colors.teal;
                              } else if (log.contains("Queued")) {
                                logIcon = Icons.schedule;
                                iconColor = Colors.orange;
                              }
                              return ListTile(
                                leading: Icon(logIcon, color: iconColor),
                                title: Text(log),
                              );
                            },
                          ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}
2
likes
160
points
152
downloads

Documentation

API reference

Publisher

verified publisherbalochcodes.com

Weekly Downloads

The ultimate offline-first engine for Flutter. Automatically queue actions/jobs while offline and sync them when connection is restored.

Homepage
Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

connectivity_plus, flutter, shared_preferences

More

Packages that depend on offline_sync_queue