[Flutter] Implementing Backup, Restore, and Auto Sync of App Data with Google Drive

2026-11-20 hit count image

How to back up and restore a Flutter app's SQLite data to the user's Google Drive without running your own server, and keep it automatically in sync across multiple devices.

flutter

Overview

An app that stores user data only in an on-device SQLite DB gives users no way to move that data when they switch devices or want to use the app on several devices at once.

Instead of building our own account system and sync server, we chose to store the DB file in the user’s Google Drive. This approach has the following advantages.

  • No separate server or sign-up is needed. Users just sign in with the Google account they already have.
  • The data is stored in the user’s own Drive storage.
  • Since the whole thing is a single file uploaded and downloaded as a unit, there is no need for per-table sync logic.

We started with a manual approach, where the user taps “Upload” / “Download” buttons on the settings screen, and later added auto sync, which keeps data in sync on its own while the app is in use. This post covers how we implemented both stages and what problems we ran into and fixed while running it in production.

Overall Structure

These are the packages we used.

PackagePurpose
google_sign_in (7.x)Google sign-in and Drive permissions (scopes)
googleapisDrive API v3 client
connectivity_plusOffline and Wi-Fi detection (auto sync)

A single file is stored on Drive at the following path.

My Drive
└── <parent folder>/
    └── <app folder>/
        └── <backup file>   ← encrypted SQLite DB file

Putting a per-app folder one level below the parent folder means that if you later build another app the same way, their files will not get mixed up.

The overall flow is simple.

  • Upload: copy the local DB → encrypt → upload to Drive
  • Download: download from Drive → decrypt → integrity check → replace the local DB

Signing In and Getting Permissions

Starting with version 7, the google_sign_in API changed significantly: sign-in (authentication) and scope permissions (authorization) are requested separately. The app calls them in this order.

final _scopes = [drive.DriveApi.driveFileScope];

await GoogleSignIn.instance.initialize(serverClientId: serverClientId);

// 1. If the user has signed in before, sign in silently without any UI.
GoogleSignInAccount? user =
    await GoogleSignIn.instance.attemptLightweightAuthentication();

// 2. If that fails, show the account picker.
user ??= await GoogleSignIn.instance.authenticate(scopeHint: _scopes);

// 3. Same for Drive permissions: silently first, then the consent screen.
var authorization =
    await user.authorizationClient.authorizationForScopes(_scopes);
authorization ??= await user.authorizationClient.authorizeScopes(_scopes);

(This code is simplified for clarity. In the real code, each call has a timeout and error handling.)

We request only one scope, drive.file (DriveApi.driveFileScope). This scope grants access only to files and folders the app itself created, so the app cannot see or modify any of the user’s other Drive files. It is less intimidating for users on the consent screen, and the app holds only the permissions it actually needs.

If the user closes the account picker or the consent screen, a GoogleSignInException is thrown with the canceled code. This is not an error, so we end quietly without showing an error message.

Creating the DriveApi Client

DriveApi from googleapis takes an http.Client. We get the auth headers from the signed-in account and pass in a small client that attaches those headers to every request.

class GoogleAuthClient extends http.BaseClient {
  final Map<String, String> header;
  final http.Client httpClient = http.Client();

  GoogleAuthClient({required this.header});

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) {
    request.headers.addAll(header);
    return httpClient.send(request);
  }
}

final header = await user.authorizationClient
    .authorizationHeaders([drive.DriveApi.driveFileScope]);
final driveApi = drive.DriveApi(GoogleAuthClient(header: header!));

There is one thing to keep in mind here. These headers contain the access token obtained at creation time, and it never changes, so once the token expires, the Drive API returns 401. This really does happen if the app stays open for a long time. How we handle it is covered later in What We Hardened in Production.

Upload: Putting the DB File on Drive

The upload proceeds in this order.

// 1. Apply changes still sitting in the WAL to the main DB file.
await dbHelper.walCheckpoint();

// 2. Instead of uploading the DB in use, copy it to a temp file and encrypt it.
await fileHelper.copyFile(dbPath, tempPath);
await fileHelper.encryptFile(tempPath, key);

// 3. Find the parent folder and the app folder, creating them if missing.
final syncFolder = await driveHelper.getFolderInfo(folderName: rootFolderName) ??
    await driveHelper.createFolder(folderName: rootFolderName);
final appFolder = await driveHelper.getFolderInfo(
      folderName: appFolderName,
      folderId: syncFolder.id,
    ) ??
    await driveHelper.createFolder(folderName: appFolderName, folderId: syncFolder.id);

// 4. Upload the file, attaching the last-modified time in appProperties.
await driveHelper.uploadFile(
  file: File(tempPath),
  folderId: appFolder.id,
  appProperties: {'localUpdatedAt': localUpdatedAtMs.toString()},
);

// 5. Delete the temp file.
await fileHelper.deleteFile(tempPath);

Let’s go over a few points.

WAL checkpoint. When SQLite runs in WAL mode, some recent changes may exist only in the -wal file and not yet in the main DB file. Copying only the main file would drop those recent changes, so we apply them with PRAGMA wal_checkpoint before copying.

Finding folders. Drive allows multiple files and folders with the same name, so you cannot look things up by “path”; you have to search with a query.

final query = "name='$folderName' "
    "and mimeType='application/vnd.google-apps.folder' "
    "and trashed=false "
    "and '$parentId' in parents";
final result = await driveApi.files.list(q: query);

Be careful not to forget trashed=false. Without it, you may find a folder the user moved to the trash and upload into it.

appProperties. Drive files can carry appProperties, app-private key-value metadata. If you store “the time this DB was last modified” there, you can later decide which side is newer by fetching only the metadata, without downloading the file. This value is at the heart of auto sync.

Download: Validating and Replacing the Received File

The download is the reverse of the upload, but the important point is that we never use the received file right away.

// 1. Look up the folders, then the file, and download it to a temp path.
final media = await driveApi.files.get(
  fileId,
  downloadOptions: drive.DownloadOptions.fullMedia,
) as drive.Media;
// Save media.stream to the temp file (tempPath).

// 2. Decrypt it.
await fileHelper.decryptFile(tempPath, key);

// 3. Check that it is a valid DB.
if (!await dbHelper.isDatabaseValid(tempPath)) {
  throw 'DownloadedDBCorrupt';
}

// 4. Only if the check passes, close the existing DB and replace it.
await dbHelper.replaceDatabase(tempPath);

The check uses SQLite’s PRAGMA quick_check to confirm the file is not corrupted, and also confirms that the tables and columns the app needs are present. A file truncated during transfer or a backup from a very old version gets rejected here, and the existing local DB stays as it is. Because this operation overwrites user data, you must keep the order so that the replacement always happens after validation.

Auto Sync: What to Compare

In the manual approach, the user picks the direction (upload or download), but with auto sync the app has to decide on its own. To answer “Which is newer, local or Drive?”, we use the following four timestamps.

SymbolMeaningStored in
LWhen local user data was last modifiedsync_metadata table in local DB
SWhen the last sync succeededsync_metadata table in local DB
RappProperties.localUpdatedAt of the Drive fileDrive
R0The value of R seen at the last syncsync_metadata table in local DB

With these values we decide separately whether “the local side changed” and whether “the remote side changed”.

final localChanged = L > S;                        // local changed since the last sync
final remoteChanged = R != null && (R0 == null || R > R0); // another device uploaded something new

Combining these two values with a few special cases, the decisions break down as follows.

SituationDecision
No file on Drive, and there is local dataUpload (first upload)
File exists on Drive, and this device has no sync historyDownload (new device)
Only the remote changedDownload
Only the local side changedUpload
Both changed (conflict)The newer one wins (Last-Write-Wins)
Nothing changedDo nothing

We pulled this decision out into a pure function (decideAction) with no I/O at all. That makes it easy to write unit tests for each input combination, and lets us verify the most error-prone part of the sync logic separately from the network.

Why not use Drive’s modifiedTime? At first it seemed enough to compare the Drive file’s modified time with the local modification time, but that approach cannot tell “what I just uploaded” apart from “what another device uploaded”, because once an upload finishes, the remote file’s modified time is always the latest. So we chose to upload the local modification time (L) together with the file as appProperties, and remember the last value we saw (R0). Since the file and its metadata go up in a single request, the two can never get out of step.

Keep the conflict policy simple. We also considered merging table by table when both sides change, but writing merge rules for each kind of data was too costly and risky. When one person alternates between several devices, editing both sides at the same time is rare, so we use the simple rule “the newer one wins” and, when a conflict happens, show a snackbar saying which side was kept.

Ask on a new device. There is one case we do not handle automatically, though. If a user has already been using the app on a new device and building up data there, and then turns on auto sync, the rule says “new device → download”, and the data built up on that device would be lost. Only in this case do we show a dialog that lets the user choose between “Use Drive data / Use this device’s data / Later”.

Auto Sync: When to Run

We first considered syncing periodically in the background, but gave up on it.

  • On iOS, the OS decides when background tasks (BGTaskScheduler) run, and execution is not guaranteed.
  • On Android, too, Doze mode and battery optimization make periodic tasks unreliable.
  • This is not data that needs to be reflected in real time, like in a messenger.

So we run sync only while the app is in the foreground, at the following four points.

TriggerDebounce
Right after app launchNone (once)
Returning from background to foreground30 seconds
User data changed5 seconds
Cellular/offline → Wi-Fi30 seconds (shared with foreground return)

The data-change trigger is called together with the L update at the end of the code that writes user data to the DB. When the user performs several actions in a row, changes keep coming, so a 5-second debounce makes sync run only once after the last change.

We also added the following rules.

  • No concurrent runs: If a sync is already in progress, a new trigger waits for the result of the running one. If the user is doing a manual upload or download, auto sync steps aside.
  • Retries: Only transient failures such as server errors are retried, up to 3 attempts in total at 2- and 4-second intervals. Results like signed out or offline are not retried.
  • Wi-Fi only option: On by default, so auto sync does not run on cellular. Instead, it syncs as soon as Wi-Fi connects, so the delay is small.
  • No sign-in UI on the automatic path: An account picker that pops up when the user did not tap anything is confusing. Auto sync only tries silent sign-in (attemptLightweightAuthentication). If that fails, it shows a “sign-in required” status at the top of the screen so the user can tap it and sign in again.

What We Hardened in Production

The basic feature works as described above, but on real user devices a wider variety of failures occurred than we expected. Here are the main things we hardened while watching errors come in through Crashlytics.

401: Re-authenticate Only Once When the Token Expires

As mentioned earlier, the token in the auth headers expires. When the Drive API returns 401, we discard the session, get a new token through silent sign-in, and then retry the same request exactly once. If the retry also returns 401, we treat the session as truly dead and ask the user to sign in again on their next manual action.

Re-authentication Landed on a Different Account

On Android, even silent sign-in can sometimes show an account picker sheet. If the user picks a different account there, you can end up uploading account A’s data to account B’s Drive, or overwriting A’s data with B’s backup.

So before every Drive request, we check that “the account at the start of the operation” and “the currently signed-in account” are the same, and stop if they differ. We also remember the first account that synced successfully, and block auto sync if it tries to run under a different account. Because an account switch leads directly to data loss, we treated this part most conservatively.

Splitting 403 by Reason

A 403 can have several causes, so the status code alone cannot tell you how to respond. We look at errors[].reason of the Drive API error (DetailedApiRequestError) and split it as follows.

DriveFailureKind classifyDriveFailure(Object e) {
  if (e is drive.DetailedApiRequestError) {
    if (e.status == 403) {
      final reasons = [for (final d in e.errors) d.reason];
      if (reasons.isNotEmpty &&
          reasons.every((r) => r == 'storageQuotaExceeded')) {
        return DriveFailureKind.storageQuotaExceeded;
      }
      if (reasons.isNotEmpty &&
          reasons.every((r) => r == 'userRateLimitExceeded' ||
                               r == 'rateLimitExceeded')) {
        return DriveFailureKind.rateLimited;
      }
      return DriveFailureKind.other;
    }
    if (e.status == 429 || (e.status ?? 0) >= 500) {
      return DriveFailureKind.transient;
    }
  }
  return DriveFailureKind.other;
}
  • Out of storage (storageQuotaExceeded): Retrying will not help. We tell the user once that their Drive is full and stop auto upload for that session, so the failure notice does not repeat every time the data changes.
  • Rate limit exceeded / server errors: Treated as transient and retried. We also report the error only when the final attempt fails.
  • Any other 403: Unknown errors are not hidden; they are reported as is.

This classification relies on the error response having its errors array filled in. Our uploads currently use multipart, so it is filled in, but switching to resumable uploads may change the response format, so check this as well if you do.

Adding Timeouts to Native Calls

Occasionally, a native call in google_sign_in would stop responding and hang. When that happens, the sync button stays in its loading state forever. So we added a 15-second timeout to calls without UI, such as initialize, silent sign-in, and permission checks, and a 60-second timeout to interactive calls where the user picks an account, and we report which stage hung as part of the error.

Connectivity Change Events in the Background on iOS

When we kept subscribing to the connectivity_plus connectivity change stream, there were cases on iOS where events delivered while the app was in the background caused problems. We avoided this by cancelling the subscription when the app goes to paused and subscribing again when it returns to resumed. Auto sync only runs in the foreground anyway, so there is no need to listen for connectivity changes in the background.

Summary

  • By uploading and downloading a single DB file to Google Drive, you can build data migration and sync between devices without a server.
  • Request only the drive.file scope, so the app can access only the files it created.
  • Run a WAL checkpoint before uploading, and replace the DB with a downloaded file only after it passes an integrity check.
  • Decide which side is newer from the modification time attached in appProperties, without downloading the file. modifiedTime alone cannot tell what you uploaded apart from what another device uploaded.
  • Pull the comparison logic out into a pure function with no I/O and test each combination.
  • Run auto sync only at defined points while in the foreground, with debouncing and limited retries. Never show sign-in UI on the automatic path.
  • In production, the code that handles situations outside the happy path, such as token expiry (401), account switches, running out of storage (403), and hung native calls, ends up far larger than the main flow. Account mix-ups in particular lead directly to data loss, so it is best to guard against them most conservatively.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.



SHARE
Twitter Facebook RSS