Tutorial
4 min read

Building a Flutter Offline-First App with Local Storage and Sync

Learn how to build a robust Flutter offline-first app using local storage and background sync strategies to deliver a seamless user experience.

Rehman Farouq

Flutter & Next.js Developer

Users expect mobile applications to remain functional even when network connectivity is intermittent or completely absent. Designing a Flutter offline-first app requires storing data locally on the device first and synchronizing changes with a remote backend when a stable connection becomes available. This architectural approach shifts the primary data source from the cloud to the device itself, significantly improving responsiveness and reliability. This guide details the practical patterns and implementation strategies required to build a persistent, synchronized mobile client using local databases and queue-based sync mechanisms.

Choosing the Right Local Storage Solution

Before implementing synchronization logic, you must select an appropriate local storage mechanism based on your data structure and query complexity. For simple key-value pairs, lightweight storage solutions work well. However, relational data structures or large datasets require a robust embedded database. When structuring your Flutter offline first app, SQLite or object stores provide the relational capabilities needed to manage complex state transitions and offline mutations safely.

Consider the volume of data your application needs to persist locally. If your application handles relational records, foreign keys, and complex filtering queries, an embedded SQL database provides standard query capabilities. If you are dealing with simpler document structures, key-value stores might reduce boilerplate code. Regardless of the chosen storage engine, the database abstraction layer must isolate the user interface from direct database operations. You can reference patterns from the Flutter Clean Architecture and MVVM Setup Guide to structure your data layers cleanly.

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class LocalDatabase {
  static final LocalDatabase instance = LocalDatabase._init();
  static Database? _database;

  LocalDatabase._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('app_database.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);
    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE items (
        id TEXT PRIMARY KEY,
        title TEXT NOT NULL,
        isSynced INTEGER NOT NULL
      )
    ''');
  }
}

Designing the Offline Data Model and Mutation Queue

An offline-first architecture requires explicit tracking of local changes that have not yet been acknowledged by the remote server. When a user creates, updates, or deletes a record while offline, the application writes the change directly to the local database and records the operation in a persistent mutation queue. This mutation queue acts as the source of truth for pending network requests, ensuring that no user actions are lost if the app closes unexpectedly.

Each entity in your local database should include sync metadata fields, such as a synchronization status flag and a last-modified timestamp. When a write operation occurs, the local record is marked as pending, and a corresponding queue entry is created with the payload and operation type. Maintaining this queue persistently guarantees that your application can resume synchronization across application restarts without relying on transient in-memory state.

class MutationQueueService {
  final Database db;

  MutationQueueService(this.db);

  Future<void> enqueueMutation(String action, Map<String, dynamic> payload) async {
    await db.insert('mutation_queue', {
      'id': DateTime.now().toIso8601String(),
      'action': action,
      'payload': payload.toString(),
      'created_at': DateTime.now().millisecondsSinceEpoch,
    });
  }
}

Implementing Network Connectivity Monitoring

To synchronize local changes with a remote server, your application must detect changes in network availability. Relying solely on a single boolean check when an action occurs is insufficient; the app must continuously listen for connectivity updates to trigger background synchronization routines automatically when a stable connection returns.

When implementing connectivity listeners, guard against false positives where a network interface is active but lacks actual internet access. Combining connectivity state streams with a lightweight ping or health check ensures that the synchronization engine only attempts to communicate with the remote server when requests are likely to succeed. When the network status transitions from offline to online, the synchronization worker reads the pending mutation queue and begins dispatching payloads.

import 'package:connectivity_plus/connectivity_plus.h';

class ConnectivityService {
  final Connectivity _connectivity = Connectivity();

  Stream<bool> get onConnectivityChanged {
    return _connectivity.onConnectivityChanged.map((result) {
      return result != ConnectivityResult.none;
    });
  }

  Future<bool> hasInternetConnection() async {
    final result = await _connectivity.checkConnectivity();
    return result != ConnectivityResult.none;
  }
}

Building the Synchronization Engine and Conflict Resolution

Synchronization is more than simply pushing local changes to the cloud. A robust sync engine must handle bidirectional data flow, handling downloads of remote updates while uploading local mutations. The engine processes the mutation queue sequentially, sending each operation to the remote API. Upon receiving a successful response, the local record updates its sync status, and the corresponding queue entry is removed.

Conflicts arise when a record is modified both locally and remotely during an offline period. Your application requires a deterministic conflict resolution strategy. Common strategies include last-write-wins based on timestamps, server-wins, or client-wins. For complex business logic, you may need to surface conflict resolution options to the user, though automated timestamp comparisons are generally sufficient for standard CRUD applications. Ensure your package selection aligns with stable utility libraries; you can review options for handling state and network requests in the overview of 25 Essential Flutter Packages.

class SyncEngine {
  final LocalDatabase localDb;
  final ApiClient apiClient;

  SyncEngine(this.localDb, this.apiClient);

  Future<void> synchronize() async {
    final db = await localDb.database;
    final pendingMutations = await db.query('mutation_queue', orderBy: 'created_at ASC');

    for (final mutation in pendingMutations) {
      try {
        final success = await apiClient.sendMutation(mutation);
        if (success) {
          await db.delete(
            'mutation_queue',
            where: 'id = ?',
            whereArgs: [mutation['id']],
          );
        }
      } catch (e) {
        // Stop syncing if network drops during processing
        break;
      }
    }
  }
}

Handling Edge Cases and Data Integrity

Building a resilient data layer requires anticipating edge cases such as partial sync failures, database schema migrations, and storage quota limits. If a batch synchronization request fails midway through processing, the system must roll back or correctly resume from the point of failure without duplicating records on the server. Idempotent API design on the backend is essential to prevent duplicate entries when network retries occur.

Database migrations also require careful planning when updating local schemas in production applications. Write comprehensive migration scripts for your local database to handle changes between app versions seamlessly. Always wrap multi-step local storage updates in database transactions to prevent partial writes from corrupting local state if the application crashes or runs out of battery.

Key takeaways

  • Prioritize local storage as the single source of truth for user interactions to guarantee immediate UI responsiveness.
  • Maintain a persistent mutation queue for all offline write operations to prevent data loss across application restarts.
  • Use continuous connectivity monitoring to trigger automated synchronization routines when network availability is restored.
  • Implement a clear conflict resolution strategy, such as timestamp-based ordering, to handle concurrent data modifications safely.
  • Design backend APIs to be idempotent to prevent duplicate data creation during retried network sync operations.

Frequently asked questions

What is an offline-first Flutter app?

An offline-first Flutter app reads from and writes to a local database on the device first, ensuring full functionality without internet access, and synchronizes data with a remote server when connectivity returns.

Which local database is best for Flutter offline apps?

SQLite (via the sqflite package) and Isar are popular choices for relational and object-based local storage in Flutter, depending on your data complexity and query requirements.

How do you handle data conflicts during synchronization?

Conflicts are typically resolved using automated strategies like last-write-wins based on timestamps, server-wins, or by prompting the user to manually select the correct version.

Why use a mutation queue in offline-first architectures?

A mutation queue stores offline create, update, and delete operations persistently on the device so they can be executed sequentially in the correct order once connectivity is restored.

More articles