<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Muhammad Arif on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Arif on Medium]]></description>
        <link>https://medium.com/@muhammad.arif5995?source=rss-139f19ddc2f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DGKPN4jKpKNFyENm</url>
            <title>Stories by Muhammad Arif on Medium</title>
            <link>https://medium.com/@muhammad.arif5995?source=rss-139f19ddc2f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:46:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@muhammad.arif5995/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Local-First Flutter App: Seamless SQLite Export/Import to Google Drive]]></title>
            <link>https://medium.com/@muhammad.arif5995/building-a-local-first-flutter-app-seamless-sqlite-export-import-to-google-drive-de0e069f3faa?source=rss-139f19ddc2f------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0e069f3faa</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[google-drive-api]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Muhammad Arif]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 10:36:57 GMT</pubDate>
            <atom:updated>2026-07-31T10:36:57.446Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>To honor this principle, I decided to build a <em>local-first</em> application using SQLite. No third-party servers, no hidden databases. Everything lives on the user’s device. However, absolute data privacy brings up a critical UX challenge: <em>How do we ensure users don’t lose their data when they switch or lose their phones?</em></blockquote><p>The solution: <strong>Seamless Cloud Export &amp; Import via Google Drive.</strong></p><p>In this article, I will share the architecture, the OAuth 2.0 nuances, and the performance bottlenecks (and solutions) I encountered while building this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdYJAMaGeH4LqHzTvD85ow.png" /></figure><h3>1. Introduction &amp; Background</h3><p>The <em>Cloud Export/Import</em> feature is highly essential for <em>offline-first</em> applications. Users want peace of mind knowing their data has a safe backup.</p><p>In this implementation, we will use the <strong>Google Drive API</strong> and <strong>Google Sign-In</strong>. The workflow is quite straightforward:</p><ol><li><strong>Export:</strong> The app reads all tables from the local SQLite database, converts them into JSON format, temporarily saves the JSON file to a local directory, and uploads it to the user’s Google Drive account.</li><li><strong>Import:</strong> The app looks for the latest JSON backup file in Google Drive, downloads it, clears the old local data, and then inserts the data from the JSON back into SQLite.</li></ol><p>For this guide, we are utilizing the googleapis, google_sign_in, and drift (as our SQLite ORM) packages.</p><h3>2. Step-by-Step Implementation</h3><h3>Step 1: Google Cloud Console &amp; OAuth Setup</h3><p>Before writing any Flutter code, you <strong>must</strong> configure your project in the Google Cloud Console. Without this, your app won’t be authorized to use Google Sign-In or access Drive.</p><ol><li><strong>Enable Google Drive API:</strong> Go to the <a href="https://console.cloud.google.com/">Google Cloud Console</a>, select your project, navigate to <strong>APIs &amp; Services &gt; Library</strong>, search for “Google Drive API”, and enable it.</li><li><strong>Configure OAuth Consent Screen:</strong> Go to <strong>OAuth consent screen</strong>.</li></ol><ul><li>Choose <strong>External</strong> (unless you are a Google Workspace user restricting the app to your organization).</li><li>Fill in the required app information.</li><li><strong>Crucial Step for Development:</strong> While your app’s publishing status is set to <strong>“Testing”</strong>, Google strictly blocks logins. You <em>must</em> add your testing email addresses under the <strong>Test users</strong> section. Otherwise, you will encounter a 403 access_denied error when trying to log in.</li></ul><p><strong>3. Create Credentials:</strong></p><ul><li>If you are using Firebase, simply enable Google Sign-In in Firebase Authentication, add your Android SHA-1 fingerprint, and download the google-services.json (and GoogleService-Info.plist for iOS). Firebase automatically configures the OAuth Client ID for you behind the scenes!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*31l--_bdwkiyv9EhpeWPyg.png" /></figure><ul><li>If not using Firebase, go to <strong>Credentials &gt; Create Credentials &gt; OAuth client ID</strong> and set it up manually for Android and iOS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*2Su1zX5JOKdBt1uXAGVYiQ.png" /></figure><h4>How to Get SHA-1 Fingerprint for Firebase (Google Sign-In Android)</h4><p>To use <strong>Google Sign-In with Firebase on Android</strong>, you must add your app’s <strong>SHA-1 fingerprint</strong> to Firebase.</p><h4>Method 1: Gradle (Recommended)</h4><ol><li>Open terminal in your Flutter project</li><li>Navigate to Android folder:</li></ol><pre>cd android</pre><ol><li>Run:</li></ol><ul><li>Mac/Linux:</li></ul><pre>./gradlew signingReport</pre><ul><li>Windows:</li></ul><pre>gradlew signingReport</pre><ol><li>Copy the SHA-1 from:</li></ol><pre>Variant: debug<br>SHA1: XX:XX:XX:...</pre><h4>Method 2: Keytool (Alternative)</h4><ul><li>Windows:</li></ul><pre>keytool -list -v -keystore &quot;%USERPROFILE%\.android\debug.keystore&quot; -alias androiddebugkey -storepass android -keypass android</pre><ul><li>Mac/Linux:</li></ul><pre>keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android</pre><p>Copy the SHA1 value from the output.</p><h3>Step 2: Google API Client Configuration</h3><p>The Google Drive API requires an HTTP client injected with Auth Headers (OAuth Token) from the currently logged-in user. Let’s create a <em>custom HTTP Client</em> first:</p><pre>import &#39;package:http/http.dart&#39; as http;<br><br>class GoogleAuthClient extends http.BaseClient {<br>  final Map&lt;String, String&gt; _headers;<br>  final http.Client _client = http.Client();<br><br>  GoogleAuthClient(this._headers);<br><br>  @override<br>  Future&lt;http.StreamedResponse&gt; send(http.BaseRequest request) {<br>    return _client.send(request..headers.addAll(_headers));<br>  }<br>}</pre><blockquote>The OAuth 2.0 Flow: Firebase vs. Google Workspace</blockquote><blockquote>One of the most confusing parts of integrating Google Drive in a Flutter app is navigating the authentication flow, especially if you are also using Firebase.</blockquote><blockquote><strong>The Golden Rule:</strong> Firebase Authentication tokens cannot be used to access Google Workspace APIs (like Google Drive or Google Sheets).</blockquote><blockquote>When users click “Sign in with Google,” you must explicitly request the Drive API scope <em>before</em> authenticating with Firebase.</blockquote><pre>import &#39;package:google_sign_in/google_sign_in.dart&#39;;<br>import &#39;package:googleapis/drive/v3.dart&#39; as drive;<br><br>final GoogleSignIn _googleSignIn = GoogleSignIn(scopes: [drive.DriveApi.driveFileScope]);</pre><blockquote>When you want to export or import data, do not use FirebaseAuth.instance.currentUser. Instead, extract the raw Auth Headers from the GoogleSignInAccount:</blockquote><pre>final account = _googleSignIn.currentUser ?? await _googleSignIn.signIn();<br>if (account == null) throw Exception(&quot;User not authenticated&quot;);<br>final authHeaders = await account.authHeaders;<br>final client = GoogleAuthClient(authHeaders);<br>final driveApi = drive.DriveApi(client);</pre><h3>Step 3: Initialize Google Sign-In with Drive Scope</h3><p>When triggering Google Sign-In, we <strong>must</strong> include the drive.file scope. This scope is highly secure and recommended because it only gives our app access to files created by our app itself (meaning the app cannot see the user&#39;s personal photos, documents, or other Drive files).</p><pre>import &#39;package:google_sign_in/google_sign_in.dart&#39;;<br>import &#39;package:googleapis/drive/v3.dart&#39; as drive;<br><br>class AuthBackupDataSourceImpl implements AuthBackupDataSource {<br>  final DatabaseImpl databaseImpl;<br>  final GoogleSignIn _googleSignIn = GoogleSignIn(<br>    scopes: [drive.DriveApi.driveFileScope]<br>  );<br><br>  AuthBackupDataSourceImpl({required this.databaseImpl});<br>  <br>  // ... authentication methods<br>}</pre><h3>Step 4: Export Logic (Data Backup)</h3><p>The export process involves three main stages: Database Query -&gt; JSON Conversion -&gt; Upload to Drive.</p><pre>@override<br>Future&lt;void&gt; exportAndUploadToDrive() async {<br>  // 1. Authenticate User<br>  final account = _googleSignIn.currentUser ?? await _googleSignIn.signIn();<br>  if (account == null) throw Exception(&quot;User not authenticated&quot;);<br><br>  final authHeaders = await account.authHeaders;<br>  final client = GoogleAuthClient(authHeaders);<br>  final driveApi = drive.DriveApi(client);<br><br>  // 2. Fetch all data from SQLite (using Drift)<br>  final users = await databaseImpl.select(databaseImpl.user).get();<br>  final banks = await databaseImpl.select(databaseImpl.banks).get();<br>  final wallets = await databaseImpl.select(databaseImpl.wallets).get();<br>  final categories = await databaseImpl.select(databaseImpl.categories).get();<br>  final budget = await databaseImpl.select(databaseImpl.budget).get();<br>  final transactions = await databaseImpl.select(databaseImpl.transactions).get();<br><br>  // 3. Convert to Map and Encode to JSON<br>  final backupData = {<br>    &quot;user&quot;: users.map((e) =&gt; e.toJson()).toList(),<br>    &quot;banks&quot;: banks.map((e) =&gt; e.toJson()).toList(),<br>    &quot;wallets&quot;: wallets.map((e) =&gt; e.toJson()).toList(),<br>    &quot;categories&quot;: categories.map((e) =&gt; e.toJson()).toList(),<br>    &quot;budget&quot;: budget.map((e) =&gt; e.toJson()).toList(),<br>    &quot;transactions&quot;: transactions.map((e) =&gt; e.toJson()).toList(),<br>  };<br><br>  String jsonData = jsonEncode(backupData);<br><br>  // 4. Save temporarily to the device&#39;s local storage<br>  final directory = await getTemporaryDirectory();<br>  final file = File(&quot;${directory.path}/backup.json&quot;);<br>  await file.writeAsString(jsonData);<br><br>  // 5. Upload to Google Drive<br>  var driveFile = drive.File();<br>  // Assign a unique name using a timestamp<br>  driveFile.name = &quot;app_backup_${DateTime.now().millisecondsSinceEpoch}.json&quot;;<br>  driveFile.mimeType = &quot;application/json&quot;;<br><br>  var media = drive.Media(file.openRead(), file.lengthSync());<br>  await driveApi.files.create(driveFile, uploadMedia: media);<br>}</pre><h3>Step 5: Import Logic (Data Restore)</h3><p>The import process acts in reverse: Search for the File in Drive -&gt; Download -&gt; Parse JSON -&gt; Insert into SQLite.</p><pre>@override<br>Future&lt;void&gt; importAndRestoreFromDrive() async {<br>  // 1. Authenticate &amp; Initialize Client<br>  final account = _googleSignIn.currentUser ?? await _googleSignIn.signIn();<br>  if (account == null) throw Exception(&quot;User not authenticated&quot;);<br><br>  final authHeaders = await account.authHeaders;<br>  final client = GoogleAuthClient(authHeaders);<br>  final driveApi = drive.DriveApi(client);<br><br>  // 2. Search for the latest JSON backup file in Drive<br>  var fileList = await driveApi.files.list(<br>    q: &quot;name contains &#39;app_backup&#39; and mimeType = &#39;application/json&#39; and trashed = false&quot;,<br>    orderBy: &quot;createdTime desc&quot;,<br>  );<br><br>  if (fileList.files == null || fileList.files!.isEmpty) return;<br>  String fileId = fileList.files!.first.id!;<br><br>  // 3. Clear old data to prevent duplicates or conflicts<br>  await databaseImpl.delete(databaseImpl.transactions).go();<br>  await databaseImpl.delete(databaseImpl.wallets).go();<br>  await databaseImpl.delete(databaseImpl.budget).go();<br>  // Delete only custom categories (keep default ones)<br>  await (databaseImpl.delete(databaseImpl.categories)<br>    ..where((tbl) =&gt; tbl.isDefault.equals(false)))<br>      .go();<br><br>  // 4. Download the file from Drive<br>  drive.Media media = await driveApi.files.get(<br>    fileId,<br>    downloadOptions: drive.DownloadOptions.fullMedia,<br>  ) as drive.Media;<br><br>  List&lt;int&gt; bytes = [];<br>  await for (var data in media.stream) {<br>    bytes.addAll(data);<br>  }<br><br>  // 5. Parse JSON<br>  String jsonString = utf8.decode(bytes);<br>  Map&lt;String, dynamic&gt; backupData = jsonDecode(jsonString);<br><br>  // 6. Insert data into the Database (Wrap in a transaction for safety &amp; speed)<br>  await databaseImpl.transaction(() async {<br>    if (backupData.containsKey(&#39;user&#39;)) {<br>      for (var item in backupData[&#39;user&#39;]) {<br>        await databaseImpl.into(databaseImpl.user).insert(UserData.fromJson(item), mode: InsertMode.insertOrReplace);<br>      }<br>    }<br>    // Repeat the insertion loop for banks, wallets, categories, budget, and transactions<br>    if (backupData.containsKey(&#39;transactions&#39;)) {<br>      for (var item in backupData[&#39;transactions&#39;]) {<br>        await databaseImpl.into(databaseImpl.transactions).insert(Transaction.fromJson(item), mode: InsertMode.insertOrReplace);<br>      }<br>    }<br>  });<br>}</pre><p><a href="https://youtu.be/kqwZQ49DZ2w">https://youtu.be/kqwZQ49DZ2w</a></p><h3>3. Problems and Bottlenecks</h3><p>Although the architecture above runs perfectly for initial use and smaller datasets, I quickly realized there are <strong>performance bottlenecks</strong> if the app starts holding tens of thousands of transaction records:</p><ol><li><strong>Out of Memory (OOM):</strong> Pulling 100,000 rows of data from SQLite into the device’s RAM (as a List&lt;Map&gt;) all at once can cause the app to crash (Force Close), especially on low-end Android devices.</li><li><strong>UI Freeze (Jank):</strong> The jsonEncode() and jsonDecode() processes run <em>synchronously</em> on the Dart Main Thread. Converting a massive JSON payload will freeze your app&#39;s UI and animations for several seconds.</li></ol><p><strong>Optimization Plans:</strong></p><ul><li>To overcome the UI freeze, the JSON encoding/decoding process should be moved to a <em>background thread</em> using Flutter’s compute() function or an Isolate.</li><li>However, the ultimate best practice is to <strong>directly back up the raw </strong><strong>.db SQLite file</strong> to Google Drive, rather than converting it to JSON. This entirely bypasses the CPU-heavy conversion process and results in a much smaller backup file size.</li></ul><h3>4. Conclusion</h3><p>Building a <em>local-first</em> application doesn’t mean you have to sacrifice the convenience of cloud backups. By leveraging the Google Drive API, we can provide total peace of mind to our users without incurring backend database server costs.</p><p>The approach of converting SQLite to JSON is great for cross-platform data readability, but it must be heavily optimized as user data grows.</p><p>Do you have a different approach or experience handling local data backups in Flutter? I’d love to hear your thoughts — let’s discuss in the comments section!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0e069f3faa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>