Adding in-app purchases to your Flutter app

1. Introduction

Adding in-app purchases to a Flutter app requires configuring the Apple App Store and Google Play Store, verifying purchase tokens on a trusted backend, and granting entitlements such as consumable currency, one-time upgrades, or recurring subscription perks.

In this codelab, you collaborate with Google Antigravity to build Dash Clicker—a mobile clicker game that uses the Dash mascot as currency—and pair it with a Dart shelf backend service and Cloud Firestore to validate and track three types of in-app purchases:

  1. Consumable (dash_consumable_2k): A repeatable purchase that immediately grants the player 2,000 Dashes and can be bought multiple times.
  2. Non-consumable (dash_upgrade_3d): A permanent one-time upgrade that transforms the classic Dash mascot into a modern 3D Dash forever.
  3. Subscription (dash_subscription_doubler): An auto-renewing subscription that multiplies passively generated clicks while the subscription remains active.

Dash Clicker home screen showing the classic Dash mascot and tap counter

Dash Clicker purchase screen listing available in-app products and past purchases

Dash Clicker home screen after purchasing the 3D Dash upgrade

What you'll build

  • A Flutter mobile app (app/) styled with material_ui and cupertino_ui that queries store products, initiates purchases, and reacts to real-time purchase streams.
  • A Dart shelf backend server (dart-backend/) that verifies purchase receipts with Google Play and the App Store, polls store billing events, and records purchase states in Cloud Firestore.

Your learning journey

This codelab guides you through building and connecting the full-stack in-app purchase flow step by step:

  1. Set up the development environment - Install Flutter and Google Antigravity, prompt Antigravity to scaffold the Dash Clicker starter project (app/), and configure your iOS bundle identifier and Android applicationId.
  2. Install the plugin - Prompt Antigravity to add in_app_purchase and in_app_purchase_platform_interface to app/.
  3. Set up the App Store - Register your App ID, create a sandbox test account, and configure the three products in App Store Connect.
  4. Set up the Play Store - Create your app in Google Play Console, prompt Antigravity to configure release keystore signing in Gradle, upload an initial app bundle, add license testers, and configure the products.
  5. Set up Firebase - Enable Google Sign-In and Cloud Firestore in the Firebase console, run flutterfire configure, and configure Android SHA-1 fingerprints and iOS URL schemes.
  6. Listen to purchase updates - Prompt Antigravity to add a testable IAPConnection wrapper, subscribe to purchaseStream, and test the app with TestIAPConnection.
  7. Make purchases - Prompt Antigravity to wrap ProductDetails in PurchasableProduct, query store products, trigger buyConsumable and buyNonConsumable, and complete pending purchases.
  8. Set up the backend - Prompt Antigravity to scaffold the dart-backend/ server with IapRepository and configure service account credentials.
  9. Verify purchases - Prompt Antigravity to require Firebase login on PurchasePage, post purchase tokens to /verifypurchase, and implement GooglePlayPurchaseHandler and AppStorePurchaseHandler.
  10. Keep track of purchases - Prompt Antigravity to poll Google Cloud Pub/Sub and the App Store Server API on the backend and synchronize entitlements back to the Flutter client using IAPRepo.

What you'll learn

  • How to collaborate with Google Antigravity to iteratively build and customize a full-stack Flutter in-app purchase app and Dart backend.
  • How to configure App Store Connect and Google Play Console with consumable, non-consumable, and subscription products.
  • How to query products, initiate purchases, and handle purchase streams with the in_app_purchase plugin.
  • How to verify Google Play and App Store purchase tokens on a Dart backend and store them in Cloud Firestore.
  • How to process store billing events and synchronize subscription and upgrade entitlements across devices.

Prerequisites

  • Basic familiarity with Flutter widgets, Dart syntax, and Provider state management.
  • An Apple Developer account (to test App Store purchases on iOS), a Google Play Developer account (to test Play Store purchases on Android), or both.
  • A Firebase account and the Firebase CLI.

2. Set up the development environment

Editor

This codelab uses Google Antigravity as your AI-first development environment. In each step, you prompt Antigravity to generate or evolve your Flutter client (app/) and Dart backend (dart-backend/), inspect the generated code, and optionally explore variations.

Install Flutter

The most up-to-date instructions on installing the Flutter SDK are always on docs.flutter.dev.

For this codelab, install the following software:

  1. Flutter SDK
  2. Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
  3. Compiler software for your chosen mobile target (Android Studio to target Android, or Xcode to target iOS).

Prompt Antigravity to create the starter project

  1. Launch Google Antigravity and open an empty workspace directory where you'd like to build both your Flutter app (app/) and Dart server (dart-backend/). Choose a path that doesn't require elevated privileges or contain spaces, such as a folder in your home directory or C:\src\.
  2. In the Antigravity agent chat panel, send the following prompt to scaffold the Dash Clicker starter app in app/:
Create a new empty Flutter project in `app/` named `dashclicker` targeting Android and iOS (`flutter create app --project-name dashclicker --empty --platforms android,ios`). Add the `cloud_firestore`, `cupertino_icons`, `firebase_auth`, `firebase_core`, `google_sign_in`, `http`, `intl`, `provider`, `logging`, `material_ui`, and `cupertino_ui` packages. Download `dash_old.png` and `dash.png` from `https://raw.githubusercontent.com/flutter/codelabs/main/in_app_purchases/step_00/app/assets/dash_old.png` and `https://raw.githubusercontent.com/flutter/codelabs/main/in_app_purchases/step_00/app/assets/dash.png` into `app/assets/` and register `assets/` under `flutter: assets:` in `app/pubspec.yaml`. Set `minSdk = 23` in `app/android/app/build.gradle.kts`, and add `GIDClientID` and `CFBundleURLTypes` placeholders in `app/ios/Runner/Info.plist`. Scaffold the Dash Clicker starter files using `package:material_ui/material_ui.dart` and `package:cupertino_ui/cupertino_ui.dart`:
- `lib/constants.dart` defining `cloudRegion = 'europe-west1'`, `storeKeyConsumable = 'dash_consumable_2k'`, `storeKeyUpgrade = 'dash_upgrade_3d'`, `storeKeySubscription = 'dash_subscription_doubler'`, and `serverIp = '192.168.178.46'`
- `lib/firebase_options.dart` with a placeholder `DefaultFirebaseOptions` for Android and iOS
- `lib/model/firebase_state.dart` (`enum FirebaseState { loading, available, notAvailable }`), `lib/model/store_state.dart` (`enum StoreState { loading, available, notAvailable }`), `lib/model/purchasable_product.dart` (`enum ProductStatus { purchasable, purchased, pending }` and `PurchasableProduct(this.title, this.description, this.price)`), and `lib/model/past_purchase.dart` (`PurchaseType`, `Store`, `Status`, and `PastPurchase.fromJson`)
- `lib/logic/dash_counter.dart` (`DashCounter extends ChangeNotifier` with `count`, `countString`, `increment()`, `addAutoIncrement()`, `applyPaidMultiplier()`, `removePaidMultiplier()`, `addBoughtDashes(int amount)`, and a 10Hz `Timer.periodic`)
- `lib/logic/dash_purchases.dart` (`DashPurchases extends ChangeNotifier` with `counter`, `storeState = StoreState.available`, mock `products`, `bool get beautifiedDash => false`, and a simulated `buy(PurchasableProduct product)` method)
- `lib/logic/dash_upgrades.dart` (`DashUpgrades extends ChangeNotifier` and `Upgrade` for `'Tim Sneath'`)
- `lib/logic/firebase_notifier.dart` (`FirebaseNotifier extends ChangeNotifier` initializing `Firebase.initializeApp`, `GoogleSignIn.instance`, `FirebaseAuth`, and `FirebaseFirestore`)
- `lib/repo/iap_repo.dart` (`IAPRepo extends ChangeNotifier` listening to Firebase auth changes and the `purchases` collection in Firestore)
- `lib/pages/home_page.dart` (`HomePage`, `DashClickerWidget`, `CounterStateWidget`, and `UpgradeList`), `lib/pages/login_page.dart` (`LoginPage`), and `lib/pages/purchase_page.dart` (`PurchasePage`, `_PurchasesLoading`, `_PurchasesNotAvailable`, `_PurchaseList`, `_PurchaseWidget`, and `PastPurchasesWidget`)
- `lib/main.dart` (`MyApp` and `MyHomePage` providing `FirebaseNotifier`, `DashCounter`, `DashUpgrades`, `IAPRepo`, and `DashPurchases` using `MultiProvider` with a `BottomNavigationBar` switching between `HomePage` and `PurchasePage`)
- `test/widget_test.dart` pumping `const MyApp()` and verifying `find.text('Tim Sneath')`.

Understanding the generated starter code

Antigravity creates the app/ Flutter project and scaffolds the Dash Clicker game architecture using Provider and ChangeNotifier:

  • app/lib/main.dart registers five ChangeNotifierProviders (FirebaseNotifier, DashCounter, DashUpgrades, IAPRepo, and DashPurchases) inside MyHomePage and switches between HomePage and PurchasePage.
  • app/lib/constants.dart defines the three store product IDs that must match the IDs you configure in App Store Connect and Google Play Console:
const cloudRegion = 'europe-west1';
const storeKeyConsumable = 'dash_consumable_2k';
const storeKeyUpgrade = 'dash_upgrade_3d';
const storeKeySubscription = 'dash_subscription_doubler';

// TODO: Replace by your own server IP
const serverIp = '192.168.178.46';

Configure your app's bundle identifier and application ID

To communicate with the App Store and Play Store, your app needs a unique reverse-domain identifier (for example, dev.flutter.dashclicker). On iOS, this is called the bundle identifier; on Android, it is the application ID. Using the same identifier on both platforms keeps configuration simpler.

First, set up the bundle identifier for iOS by opening app/ios/Runner.xcworkspace in Xcode:

Opening Runner.xcworkspace in Xcode

In Xcode's project navigator, select Runner at the top, open the Signing & Capabilities tab, select your Team, and enter your unique Bundle Identifier:

Configuring Team and Bundle Identifier in Xcode Signing & Capabilities

Next, update the Android applicationId in app/android/app/build.gradle.kts to match your chosen identifier (you can edit it directly or ask Antigravity to update applicationId in app/android/app/build.gradle.kts to your chosen ID):

Setting applicationId in android/app/build.gradle.kts

3. Install the plugin

In this step, you prompt Antigravity to add the in_app_purchase plugin and its platform interface package (used for mocking store connections in widget tests) to app/.

Prompt Antigravity to install in_app_purchase

In the Antigravity agent chat panel, send the following prompt:

In `app/`, add `in_app_purchase` to `dependencies` and `in_app_purchase_platform_interface` to `dev_dependencies` in `pubspec.yaml`.

Understanding the generated code

Antigravity runs flutter pub add in_app_purchase dev:in_app_purchase_platform_interface inside app/, updating app/pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^7.1.0
  cupertino_icons: ^2.0.0
  cupertino_ui: ^1.1.6
  firebase_auth: ^7.0.1
  firebase_core: ^5.1.0
  google_sign_in: ^7.2.0
  http: ^1.6.0
  in_app_purchase: ^3.3.1
  intl: ^0.20.3
  logging: ^1.3.0
  material_ui: ^1.11.0
  provider: ^6.1.5+1

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^6.0.0
  in_app_purchase_platform_interface: ^1.4.1
  • in_app_purchase provides the cross-platform InAppPurchase API backed by StoreKit on iOS and Google Play Billing on Android.
  • in_app_purchase_platform_interface exposes InAppPurchasePlatformAddition, which lets you implement a mock InAppPurchase client in app/test/widget_test.dart.

4. Set up the App Store

To test in-app purchases on iOS, you need to register your app in App Store Connect and configure purchasable products. You don't have to publish the app or submit it for review, but you do need an Apple Developer account. If you don't have one, enroll in the Apple Developer Program.

To use in-app purchases, you must have an active Paid Apps agreement in App Store Connect. Go to App Store Connect, and select Agreements, Tax, and Banking (or Business).

App Store Connect home dashboard highlighting Agreements, Tax, and Banking

Review the agreements for free and paid apps. View and accept the terms for Paid Apps, and enter the required tax and banking information.

App Store Connect Agreements list showing Free Apps active and Paid Apps new

When everything is configured, the status for Paid Apps changes to Active. Without an active Paid Apps agreement, StoreKit won't return your in-app products during testing.

App Store Connect Agreements list showing both Free Apps and Paid Apps active

Register an App ID

Create a new App ID in the Apple Developer Portal:

  1. Visit Apple Developer Identifiers and click the + icon next to the Identifiers header.Apple Developer Portal Identifiers list with the add button highlighted
  2. Select App IDs and click Continue.Register a new identifier screen with App IDs selected
  3. Select App as the type and click Continue.Select a type screen with App selected
  4. Enter a description and set the Bundle ID (Explicit) to the exact bundle identifier you configured in Xcode. Ensure the In-App Purchase capability is enabled, then register the identifier.Register an App ID form showing description and explicit Bundle ID

For additional details, see Apple Developer Account Help.

Create a new app and sandbox user

Create a new app in App Store Connect using your registered bundle identifier:

App Store Connect Apps menu showing the New App option

New App dialog in App Store Connect showing platform, name, language, bundle ID, and SKU fields

For more guidance on creating an app and managing agreements, see App Store Connect Help.

To test in-app purchases without real charges, create a Sandbox Apple Account in App Store Connect under Users and Access > Sandbox. You must use an email address that isn't already associated with an Apple Account.

App Store Connect Sandbox Testers list

On your test iPhone or iPad, sign in with your sandbox account under Settings > Developer > Sandbox Apple Account.

iOS Settings screen showing the Sandbox Apple Account section

iOS Settings screen showing a signed-in Sandbox Apple Account

Configure your in-app purchases

Next, configure the three purchasable items in App Store Connect:

  • dash_consumable_2k: A consumable purchase that can be bought repeatedly, granting 2,000 Dashes per purchase.
  • dash_upgrade_3d: A non-consumable upgrade purchase that can only be bought once, unlocking the 3D Dash mascot.
  • dash_subscription_doubler: An auto-renewing subscription that multiplies passive clicks while active.

App Store Connect sidebar highlighting In-App Purchases and Subscriptions

In your app's In-App Purchases (and Subscriptions) sections, create the three products with these exact Product IDs:

  1. Consumable (dash_consumable_2k):
    • Create a Consumable product with Reference Name dash consumable 2k and Product ID dash_consumable_2k.Create an In-App Purchase modal configured for dash_consumable_2k
    • Configure availability so the product is available in your sandbox user's country or region.Availability configuration for the in-app purchase
    • Set the price to \$1.99 (or local currency equivalent).Price Schedule configuration set to $1.99
    • Add a localization with Display Name Spring is in the air and Description 2000 dashes fly out.App Store Localization showing Display Name and Description
    • Upload a review screenshot. The image content doesn't matter for sandbox testing, but uploading a screenshot transitions the product to the Ready to Submit state, which is required for the app to fetch the product from StoreKit.Review Information section with an uploaded product preview image
  2. Non-consumable (dash_upgrade_3d):
    • Create a Non-Consumable product with Reference Name dash upgrade 3d and Product ID dash_upgrade_3d.
    • Set the Display Name to 3D Dash, Description to Brings your dash back to the future, and price to \$0.99.
    • Configure availability and upload a review screenshot just as you did for dash_consumable_2k.Non-consumable product configuration for dash_upgrade_3d
  3. Auto-renewing subscription (dash_subscription_doubler):
    • Under Subscriptions, create a Subscription Group named subscriptions (users can subscribe to only one product within the same group at a time, and can upgrade or downgrade within the group).Create Subscription Group dialog
    • Add an App Store localization for the subscription group.App Store Localization dialog for the subscription group
    • Inside the group, create a subscription with Reference Name dash subscription doubler and Product ID dash_subscription_doubler.Create Subscription dialog for dash_subscription_doubler
    • Set the Subscription Duration to 1 Week, Display Name to Jet Engine, Description to Doubles your clicks, and price to \$0.49. Configure availability and upload a review screenshot so its status becomes Ready to Submit.Subscription duration, price, and localization settings

Your products should now appear in App Store Connect with the Ready to Submit status:

In-App Purchases list showing dash_consumable_2k and dash_upgrade_3d as Ready to Submit

Subscriptions list showing dash_subscription_doubler as Ready to Submit

5. Set up the Play Store

To test in-app purchases on Android, you need a Google Play Developer account. If you don't have one yet, register for a Google Play Developer account.

Create a new app

Create a new app in the Google Play Console:

  1. Open the Google Play Console.
  2. Select All apps > Create app.
  3. Choose a default language and enter an app name (you can change this later).
  4. Select Game as the app type and Free as the pricing model.
  5. Complete the Developer Program Policies and US export laws declarations, then select Create app.

After creating the app, complete the initial Set up your app tasks on the dashboard:

Google Play Console dashboard showing the Set up your app checklist

Sign the application

To test Google Play Billing, you must upload at least one signed release appbundle to a testing track in Google Play Console.

Create a keystore

If you don't already have an upload keystore, generate one from the terminal.

On macOS or Linux:

keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key

On Windows:

keytool -genkey -v -keystore c:\Users\USER_NAME\key.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias key

Create app/android/key.properties

Create app/android/key.properties containing a reference to your keystore:

storePassword=<password from previous step>
keyPassword=<password from previous step>
keyAlias=key
storeFile=<location of the key store file, such as /Users/<user name>/key.jks>

Prompt Antigravity to configure release signing in Gradle

Send the following prompt in Antigravity to wire up release signing in app/android/app/build.gradle.kts:

Update `app/android/app/build.gradle.kts` to load `key.properties` into a `Properties` object if the file exists, configure a `release` signing config inside `signingConfigs` using `keyAlias`, `keyPassword`, `storeFile`, and `storePassword`, and assign `signingConfigs.getByName("release")` to the `release` build type when `key.properties` is present.

Antigravity updates app/android/app/build.gradle.kts to load key.properties and sign release builds:

val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(FileInputStream(keystorePropertiesFile))
}

android {
    // ...
    signingConfigs {
        create("release") {
            keyAlias = keystoreProperties["keyAlias"] as String?
            keyPassword = keystoreProperties["keyPassword"] as String?
            storeFile = keystoreProperties["storeFile"]?.let { file(it) }
            storePassword = keystoreProperties["storePassword"] as String?
        }
    }

    buildTypes {
        release {
            signingConfig = signingConfigs.getByName("release")
        }
    }
}

Upload your first build

Build a signed release app bundle from app/:

cd app
flutter build appbundle

The release bundle is written to app/build/app/outputs/bundle/release/app-release.aab.

In the Google Play Console, navigate to Test and release > Testing > Closed testing, create a closed testing release, upload app-release.aab, and click Save > Review release > Start rollout to Closed testing.

Set up test users

To test in-app purchases on Android, add your testers' Google Accounts in two places in the Google Play Console:

  1. Testing track testers: Go to Test and release > Testing > Internal testing (or Closed testing), open the Testers tab, click Create email list, add your testers' email addresses, select the list, and click Save changes.Google Play Console Internal testing Testers tab
  2. License testers: Return to the All apps view, select Settings > License testing, add the same tester email addresses, set License response to RESPOND_NORMALLY, and click Save changes.Google Play Console License testing settings

Configure your in-app purchases

Configure the same three product IDs in the Google Play Console:

  • dash_consumable_2k: Consumable purchase granting 2,000 Dashes.
  • dash_upgrade_3d: Non-consumable one-time 3D Dash upgrade.
  • dash_subscription_doubler: Auto-renewing click-multiplier subscription.

First, create the one-time products (dash_consumable_2k and dash_upgrade_3d):

  1. Select your app in the Google Play Console and navigate to Monetize with Play > Products > In-app products.
  2. Click Create product.Google Play Console In-app products page with Create product button
  3. Enter the exact Product ID (dash_consumable_2k), name, description, and price, then click Save and Activate.
  4. Repeat the process for dash_upgrade_3d.

Next, create the subscription (dash_subscription_doubler):

  1. Navigate to Monetize with Play > Products > Subscriptions and click Create subscription.Google Play Console Subscriptions page with Create subscription button
  2. Enter the Product ID (dash_subscription_doubler), add a base plan with a weekly billing period and price, then Save and Activate it.

6. Set up Firebase

Using a backend service with Cloud Firestore to verify and track purchases gives your app several security advantages:

  • You verify transactions directly with Google Play and Apple servers.
  • You can react to server-side billing events (such as renewals or cancellations).
  • You store a single source of truth in Cloud Firestore associated with each authenticated user.
  • Users can't unlock premium perks by tampering with their device clock.

Create a Firebase project

  1. Open the Firebase console and create a new Firebase project (for example, Dash Clicker).
  2. Navigate to Build > Authentication, click Get started, open the Sign-in method tab, and enable the Google sign-in provider.Firebase Authentication Sign-in method tab showing Google enabled
  3. Navigate to Build > Firestore Database and create a database.Firebase console Cloud Firestore creation banner
  4. Open the Rules tab in Cloud Firestore and publish the following security rules so authenticated users can read only their own purchase documents:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /purchases/{purchaseId} {
      allow read: if request.auth != null && request.auth.uid == resource.data.userId
    }
  }
}

Set up Firebase for Flutter

Follow the FlutterFire setup guide to install the FlutterFire CLI, then run flutterfire configure inside app/:

cd app
flutterfire configure
  1. Select the Firebase project you created.
  2. Enable android and ios.
  3. Confirm yes when asked to override lib/firebase_options.dart.

Set up Firebase for Android: Debug SHA-1 certificate

Google Sign-In on Android requires registering your debug keystore's SHA-1 fingerprint in the Firebase console:

  1. In the Firebase console, open Project Overview > Project settings > General, scroll down to Your apps, and select your Android app:Firebase Project settings showing the Android app configuration and Add fingerprint button
  2. Generate a signing report from app/android/:
    cd app/android
    ./gradlew :app:signingReport
    
  3. Locate the SHA1 fingerprint under Variant: debug and Config: debug, add it to your Android app in the Firebase console, and re-run flutterfire configure in app/ so google-services.json and lib/firebase_options.dart include the updated OAuth client configuration.

Set up Firebase for iOS: Configure URL schemes

To support Google Sign-In on iOS, app/ios/Runner/Info.plist must include the REVERSED_CLIENT_ID from app/ios/Runner/GoogleService-Info.plist inside CFBundleURLTypes (see the google_sign_in iOS integration docs).

You can prompt Antigravity to copy the REVERSED_CLIENT_ID and CLIENT_ID from app/ios/Runner/GoogleService-Info.plist into app/ios/Runner/Info.plist:

Read `CLIENT_ID` and `REVERSED_CLIENT_ID` from `app/ios/Runner/GoogleService-Info.plist` and update `GIDClientID` and `CFBundleURLTypes` (`CFBundleURLSchemes`) in `app/ios/Runner/Info.plist` with those values.

In app/ios/Runner/Info.plist, the CFBundleURLTypes entry looks like this:

<key>CFBundleURLTypes</key>
<array>
	<dict>
		<key>CFBundleTypeRole</key>
		<string>Editor</string>
		<key>CFBundleURLSchemes</key>
		<array>
			<string>com.googleusercontent.apps.YOUR_REVERSED_CLIENT_ID</string>
		</array>
	</dict>
</array>

7. Listen to purchase updates

In this step, you prepare the Flutter app to listen to store purchase updates as soon as the app launches, and keep the widget tree testable by introducing an overridable IAPConnection wrapper.

Prompt Antigravity to listen to purchase updates

Send the following prompt in Antigravity:

Update `app/lib/main.dart` to define an `IAPConnection` class with a static `InAppPurchase? _instance` and a static getter and setter for `instance` (defaulting to `InAppPurchase.instance`), and set `lazy: false` on `ChangeNotifierProvider<DashPurchases>`. Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` to set `storeState = StoreState.notAvailable`, hold `final iapConnection = IAPConnection.instance` and `late StreamSubscription<List<PurchaseDetails>> _subscription`, subscribe to `iapConnection.purchaseStream.listen(_onPurchaseUpdate, onDone: _updateStreamOnDone, onError: _updateStreamOnError)` in the constructor, cancel `_subscription` in `dispose()`, and add `_onPurchaseUpdate`, `_updateStreamOnDone`, and `_updateStreamOnError` methods. Finally, update `app/test/widget_test.dart` to define `TestIAPConnection implements InAppPurchase` and set `IAPConnection.instance = TestIAPConnection()` before pumping `MyApp`.

Understanding the generated code

Eager provider initialization and IAPConnection in app/lib/main.dart

By default, Provider creates its value lazily when a widget first reads it. Because pending store transactions can arrive on purchaseStream immediately at startup, ChangeNotifierProvider sets lazy: false. In addition, IAPConnection provides a static seam so widget tests can inject a fake InAppPurchase implementation:

class IAPConnection {
  static InAppPurchase? _instance;
  static set instance(InAppPurchase value) {
    _instance = value;
  }

  static InAppPurchase get instance {
    _instance ??= InAppPurchase.instance;
    return _instance!;
  }
}
ChangeNotifierProvider<DashPurchases>(
  create: (context) => DashPurchases(context.read<DashCounter>()),
  lazy: false,
),

Subscribing to purchaseStream in app/lib/logic/dash_purchases.dart

In DashPurchases, the constructor subscribes to iapConnection.purchaseStream and dispose() cancels _subscription:

  final iapConnection = IAPConnection.instance;

  DashPurchases(this.counter) {
    final purchaseUpdated = iapConnection.purchaseStream;
    _subscription = purchaseUpdated.listen(
      _onPurchaseUpdate,
      onDone: _updateStreamOnDone,
      onError: _updateStreamOnError,
    );
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

Run and test the app

Run the widget test suite in app/ to verify that TestIAPConnection mocks the store connection cleanly:

cd app
flutter test

8. Make purchases

In this step, you replace the hardcoded mock products with live store products fetched using queryProductDetails, initiate purchases when the user taps a product, and complete transactions when updates arrive on purchaseStream.

Prompt Antigravity to load and make purchases

Send the following prompt in Antigravity:

Update `PurchasableProduct` in `app/lib/model/purchasable_product.dart` to wrap a `ProductDetails productDetails` from `package:in_app_purchase/in_app_purchase.dart`, exposing `id`, `title`, `description`, and `price` getters from `productDetails` and initializing `status = ProductStatus.purchasable`. Then update `DashPurchases` in `app/lib/logic/dash_purchases.dart` to initialize `storeState = StoreState.loading`, `products = []`, and `bool _beautifiedDashUpgrade = false` (backing `beautifiedDash`), call `loadPurchases()` in the constructor to check `iapConnection.isAvailable()` and query `{storeKeyConsumable, storeKeySubscription, storeKeyUpgrade}` with `iapConnection.queryProductDetails(ids)`, implement `buy(PurchasableProduct product)` using `PurchaseParam` to call `iapConnection.buyConsumable` for `storeKeyConsumable` and `iapConnection.buyNonConsumable` for `storeKeySubscription` and `storeKeyUpgrade`, and implement `_onPurchaseUpdate` and `_handlePurchase(PurchaseDetails purchaseDetails)` to apply `PurchaseStatus.purchased` rewards (`counter.applyPaidMultiplier()`, `counter.addBoughtDashes(2000)`, `_beautifiedDashUpgrade = true`) and call `iapConnection.completePurchase(purchaseDetails)` when `purchaseDetails.pendingCompletePurchase` is true.

Understanding the generated code

Wrapping ProductDetails in app/lib/model/purchasable_product.dart

PurchasableProduct wraps the ProductDetails returned by the store while tracking local UI ProductStatus (purchasable, purchased, or pending):

class PurchasableProduct {
  String get id => productDetails.id;
  String get title => productDetails.title;
  String get description => productDetails.description;
  String get price => productDetails.price;
  ProductStatus status;
  ProductDetails productDetails;

  PurchasableProduct(this.productDetails) : status = ProductStatus.purchasable;
}

Querying products in app/lib/logic/dash_purchases.dart

loadPurchases() first verifies that the underlying store is reachable with iapConnection.isAvailable(), then queries the three product IDs defined in app/lib/constants.dart:

  Future<void> loadPurchases() async {
    final available = await iapConnection.isAvailable();
    if (!available) {
      storeState = StoreState.notAvailable;
      notifyListeners();
      return;
    }
    const ids = <String>{
      storeKeyConsumable,
      storeKeySubscription,
      storeKeyUpgrade,
    };
    final response = await iapConnection.queryProductDetails(ids);
    products = response.productDetails
        .map((e) => PurchasableProduct(e))
        .toList();
    storeState = StoreState.available;
    notifyListeners();
  }

Initiating and completing purchases

When a user taps a product in PurchasePage, buy() constructs a PurchaseParam and dispatches consumables to buyConsumable and one-time upgrades or subscriptions to buyNonConsumable:

  Future<void> buy(PurchasableProduct product) async {
    final purchaseParam = PurchaseParam(productDetails: product.productDetails);
    switch (product.id) {
      case storeKeyConsumable:
        await iapConnection.buyConsumable(purchaseParam: purchaseParam);
      case storeKeySubscription:
      case storeKeyUpgrade:
        await iapConnection.buyNonConsumable(purchaseParam: purchaseParam);
      default:
        throw ArgumentError.value(
          product.productDetails,
          '${product.id} is not a known product',
        );
    }
  }

When the store emits updated PurchaseDetails objects on purchaseStream, _handlePurchase grants the corresponding reward and acknowledges completion by calling completePurchase:

  Future<void> _handlePurchase(PurchaseDetails purchaseDetails) async {
    if (purchaseDetails.status == PurchaseStatus.purchased) {
      switch (purchaseDetails.productID) {
        case storeKeySubscription:
          counter.applyPaidMultiplier();
        case storeKeyConsumable:
          counter.addBoughtDashes(2000);
        case storeKeyUpgrade:
          _beautifiedDashUpgrade = true;
      }
    }

    if (purchaseDetails.pendingCompletePurchase) {
      await iapConnection.completePurchase(purchaseDetails);
    }
  }

Run and test the app

Run flutter test in app/ and launch the app on your configured test device. When your store products are active, the Purchase tab displays them ready for purchase:

Dash Clicker Purchase tab displaying the three store products loaded from the store

9. Set up the backend

Before verifying and tracking purchases on a server, you'll scaffold the Dart backend service in dart-backend/ alongside app/ and configure credentials for Firebase, Google Play, and the App Store.

Prompt Antigravity to scaffold the Dart backend

In the Antigravity agent chat panel, send the following prompt to create the dart-backend/ project:

Create a Dart shelf server project in `dart-backend/` with package name `firebase_backend_dart` (`dart create -t server-shelf`). Add `googleapis: ^16.0.0`, `googleapis_auth`, `http`, and `app_store_server_sdk` to `dependencies`, and `test` to `dev_dependencies` (configuring `deprecated_member_use: ignore` in `dart-backend/analysis_options.yaml`). Create:
- `dart-backend/lib/constants.dart` defining `androidPackageId`, `appStoreIssuerId`, `appStoreKeyId`, `appStoreSharedSecret`, `bundleId`, `googleCloudProjectId`, and `googlePlayPubsubBillingTopic = 'play_billing'`
- `dart-backend/lib/helpers.dart` with `serveHandler(Handler handler)`, `listenPort()`, and `terminateRequestFuture()` listening to `SIGINT` and `SIGTERM`
- `dart-backend/lib/products.dart` defining `ProductData(this.productId, this.type)`, `enum ProductType { subscription, nonSubscription }`, and `productDataMap` for `'dash_consumable_2k'`, `'dash_upgrade_3d'`, and `'dash_subscription_doubler'`
- `dart-backend/lib/iap_repository.dart` defining `enum IAPSource { googleplay, appstore }`, `abstract class Purchase`, `NonSubscriptionPurchase`, `SubscriptionPurchase`, and `IapRepository(this.api, this.projectId)` using `package:googleapis/firestore/v1.dart` (`createOrUpdatePurchase`, `updatePurchase`, and `getPurchases`)
- `dart-backend/bin/server.dart` starting an empty `Router()` with `await serveHandler(router.call)`.

Understanding the generated code

  • dart-backend/bin/server.dart initializes a shelf_router Router and serves HTTP requests on port 8080 using serveHandler in dart-backend/lib/helpers.dart.
  • dart-backend/lib/products.dart maps each product ID (dash_consumable_2k, dash_upgrade_3d, and dash_subscription_doubler) to its ProductType (nonSubscription or subscription).
  • dart-backend/lib/iap_repository.dart encapsulates reading and writing NonSubscriptionPurchase and SubscriptionPurchase documents in the purchases collection of Cloud Firestore using FirestoreApi.

You can test that the server starts locally by running:

cd dart-backend
dart run ./bin/server.dart

Set up Firebase access

To let dart-backend/ write verified purchases to Cloud Firestore, generate a service account key:

  1. In the Firebase console, open Project settings > Service accounts and click Generate new private key.Firebase Project settings Service accounts tab showing Generate new private key
  2. Save the downloaded JSON file as dart-backend/assets/service-account-firebase.json.

Set up Google Play access

To let dart-backend/ verify Android purchases with the Google Play Android Developer API:

  1. Open the Google Play Android Developer API page in the Google Cloud Console and enable the API.Google Cloud Console page for Google Play Android Developer API
  2. Go to the Google Cloud Service accounts page and click + Create service account.Google Cloud Console Service accounts page showing Create service account
  3. Enter a service account name and click Create and continue.Service account details step
  4. Grant the Pub/Sub Subscriber role and click Done.Grant this service account access to project step showing Pub/Sub Subscriber role
  5. Open the newly created service account's actions menu and select Manage keys.Service account actions menu highlighting Manage keys
  6. Select Add key > Create new key, choose JSON, and download the key:Add key menu showing Create new keyCreate private key dialog with JSON selected
  7. Save the downloaded file as dart-backend/assets/service-account-google-play.json.
  8. Open Users and permissions in the Google Play Console, click Invite new users, and enter the service account's email address:Google Play Console Users and permissions pageGoogle Cloud Service accounts table showing the service account email address
  9. Grant View financial data and Manage orders and subscriptions permissions for your app, then click Invite user.App permissions tab showing View financial data and Manage orders and subscriptions checked

Set up Apple App Store access

To verify App Store receipts on the backend, generate an App-Specific Shared Secret:

  1. Open App Store Connect, select Apps, and choose your app.
  2. In the sidebar, navigate to General > App Information.
  3. Under App-Specific Shared Secret, click Manage, generate a new shared secret, and copy it:App Store Connect App-Specific Shared Secret sectionApp-Specific Shared Secret modal showing the generated secret

Update dart-backend/lib/constants.dart

Ensure the following constants are set in dart-backend/lib/constants.dart:

  • androidPackageId: Your Android applicationId (such as com.example.dashclicker).
  • appStoreSharedSecret: Your App Store Connect shared secret.
  • bundleId: Your iOS bundle identifier (such as com.example.dashclicker).

10. Verify purchases

When a user completes a purchase on iOS or Android, the store issues a verification token (PurchaseDetails.verificationData.serverVerificationData). Instead of trusting the client device directly, the Flutter app sends this token to dart-backend/, which verifies the token with Google Play or the App Store and records the purchase in Cloud Firestore.

PurchaseHandler class hierarchy implemented by GooglePlayPurchaseHandler and AppStorePurchaseHandler

Prompt Antigravity to verify purchases on the client and backend

Send the following prompt in Antigravity to connect the Flutter app and Dart backend verification flow:

1. In `app/`:
- Update `PurchasePage` in `app/lib/pages/purchase_page.dart` to watch `FirebaseNotifier` and return `_PurchasesLoading()` when `state == FirebaseState.loading`, `_PurchasesNotAvailable()` when `state == FirebaseState.notAvailable`, and `const LoginPage()` when `!firebaseNotifier.loggedIn`.
- Add `User? get user => FirebaseAuth.instance.currentUser;` to `FirebaseNotifier` in `app/lib/logic/firebase_notifier.dart`.
- Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` (and its provider in `app/lib/main.dart`) to accept `this.firebaseNotifier`, implement `_verifyPurchase(PurchaseDetails purchaseDetails)` that sends an HTTP `POST` request to `Uri.http('$serverIp:8080', '/verifypurchase')` with JSON body `{'source': purchaseDetails.verificationData.source, 'productId': purchaseDetails.productID, 'verificationData': purchaseDetails.verificationData.serverVerificationData, 'userId': firebaseNotifier.user?.uid}`, and update `_handlePurchase` so purchase rewards are only applied when `await _verifyPurchase(purchaseDetails)` returns `true`.

2. In `dart-backend/`:
- Create `dart-backend/lib/purchase_handler.dart` with `abstract class PurchaseHandler` defining `handleNonSubscription`, `handleSubscription`, and `verifyPurchase` switching on `productData.type`.
- Create `dart-backend/lib/google_play_purchase_handler.dart` with `GooglePlayPurchaseHandler extends PurchaseHandler` that verifies one-time purchases using `androidPublisher.purchases.products.get` and subscriptions using `androidPublisher.purchases.subscriptions.get`, parses order IDs with `extractOrderId(String orderId)` (stripping `..` renewal suffixes), maps statuses with `_nonSubscriptionStatusFrom` and `_subscriptionStatusFrom`, and saves purchases to `iapRepository`.
- Create `dart-backend/lib/app_store_purchase_handler.dart` with `AppStorePurchaseHandler extends PurchaseHandler` that validates receipts with `ITunesApi(ITunesHttpClient(ITunesEnvironment.sandbox(), loggingEnabled: true)).verifyReceipt` and saves `NonSubscriptionPurchase` and `SubscriptionPurchase` records to `iapRepository`.
- Update `dart-backend/bin/server.dart` to initialize `AndroidPublisherApi` and `FirestoreApi` from the service account JSON files in `_createPurchaseHandlers()`, register a `POST /verifypurchase` route, and extract request fields in `getPurchaseData(dynamic payload)` using Dart 3 map pattern matching.

Understanding the generated code

Gating purchases behind authentication and calling /verifypurchase

In app/lib/pages/purchase_page.dart, PurchasePage checks FirebaseNotifier and displays LoginPage until the user signs in:

    var firebaseNotifier = context.watch<FirebaseNotifier>();
    if (firebaseNotifier.state == FirebaseState.loading) {
      return _PurchasesLoading();
    } else if (firebaseNotifier.state == FirebaseState.notAvailable) {
      return _PurchasesNotAvailable();
    }

    if (!firebaseNotifier.loggedIn) {
      return const LoginPage();
    }

In app/lib/logic/dash_purchases.dart, _verifyPurchase posts the store source (google_play or app_store), productID, serverVerificationData, and the signed-in userId to the Dart backend before _handlePurchase grants the in-app reward:

  Future<bool> _verifyPurchase(PurchaseDetails purchaseDetails) async {
    final url = Uri.http('$serverIp:8080', '/verifypurchase');
    const headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
    final response = await http.post(
      url,
      body: jsonEncode({
        'source': purchaseDetails.verificationData.source,
        'productId': purchaseDetails.productID,
        'verificationData':
            purchaseDetails.verificationData.serverVerificationData,
        'userId': firebaseNotifier.user?.uid,
      }),
      headers: headers,
    );
    if (response.statusCode == 200) {
      return true;
    } else {
      return false;
    }
  }

Routing and Dart 3 pattern matching in dart-backend/bin/server.dart

On the server, POST /verifypurchase decodes the JSON request body with getPurchaseData using a Dart 3 map pattern and record return type, then delegates verification to the matching store handler:

  router.post('/verifypurchase', (Request request) async {
    final dynamic payload = json.decode(await request.readAsString());
    final (:userId, :source, :productData, :token) = getPurchaseData(payload);

    final result = await purchaseHandlers[source]!.verifyPurchase(
      userId: userId,
      productData: productData,
      token: token,
    );

    if (result) {
      return Response.ok('all good!');
    } else {
      return Response.internalServerError();
    }
  });
({String userId, String source, ProductData productData, String token})
getPurchaseData(dynamic payload) {
  if (payload case {
    'userId': String userId,
    'source': String source,
    'productId': String productId,
    'verificationData': String token,
  }) {
    return (
      userId: userId,
      source: source,
      productData: productDataMap[productId]!,
      token: token,
    );
  } else {
    throw const FormatException('Unexpected JSON');
  }
}

Verifying Google Play and App Store receipts

  • In dart-backend/lib/google_play_purchase_handler.dart, GooglePlayPurchaseHandler queries androidPublisher.purchases.products.get for one-time products and androidPublisher.purchases.subscriptions.get for subscriptions, strips ..# renewal suffixes from subscription order IDs using extractOrderId, and writes the resulting NonSubscriptionPurchase or SubscriptionPurchase to Cloud Firestore using iapRepository.
  • In dart-backend/lib/app_store_purchase_handler.dart, AppStorePurchaseHandler calls _iTunesAPI.verifyReceipt using the app_store_server_sdk package and persists each verified receipt in response.latestReceiptInfo to Cloud Firestore.

Run and test the backend

Start the backend server from dart-backend/:

cd dart-backend
dart run bin/server.dart

11. Keep track of purchases

Subscriptions can renew, expire, or be canceled outside your app. In this step, you configure the backend to poll store billing updates from Google Cloud Pub/Sub and the App Store Server API, and update the Flutter client to reactively sync the user's active entitlements from Cloud Firestore using IAPRepo.

Configure Cloud Pub/Sub and App Store Server API keys

Google Play Cloud Pub/Sub setup

  1. Set googleCloudProjectId in dart-backend/lib/constants.dart to your Google Cloud and Firebase project ID.
  2. Open the Cloud Pub/Sub Topics page in the Google Cloud Console, ensure your project is selected, and click + Create Topic.Google Cloud Pub/Sub Topics page showing the Create Topic button
  3. Set the Topic ID to play_billing (matching googlePlayPubsubBillingTopic in dart-backend/lib/constants.dart, which automatically creates a default subscription play_billing-sub), and click Create.Create a topic dialog with Topic ID play_billing
  4. Open the three-dot menu on your play_billing topic and select View permissions.Pub/Sub topic menu highlighting View permissions
  5. Click Add principal, enter google-play-developer-notifications@system.gserviceaccount.com, assign the Pub/Sub Publisher role, and click Save.Add principals panel granting Pub/Sub Publisher to google-play-developer-notifications
  6. Copy the full topic name, open your app in the Google Play Console, go to Monetize with Play > Monetization setup, paste the topic name, and click Save changes.Google Play Console Monetization setup showing the Real-time developer notifications topic name

App Store Server API key setup

  1. Sign in to App Store Connect and select Users and Access.
  2. Navigate to Integrations > Keys > In-App Purchase and click the + button to generate a new key (for example, Codelab key).
  3. Download the .p8 key file and save it as dart-backend/assets/SubscriptionKey.p8.
  4. Copy the Key ID and Issuer ID into appStoreKeyId and appStoreIssuerId in dart-backend/lib/constants.dart.

App Store Connect In-App Purchase keys list showing Issuer ID and Key ID

Prompt Antigravity to poll store events and synchronize client state

Send the following prompt in Antigravity:

1. In `dart-backend/`:
- Update `GooglePlayPurchaseHandler` in `dart-backend/lib/google_play_purchase_handler.dart` to accept `pubsub.PubsubApi pubsubApi` from `package:googleapis/pubsub/v1.dart`, start a 10-second `Timer.periodic` calling `_pullMessageFromPubSub()`, decode base64 Pub/Sub messages in `_processMessage(String data64, String? ackId)` (handling `testNotification`, `subscriptionNotification`, and `oneTimeProductNotification`), and acknowledge processed messages in `_ackMessage(String id)`.
- Update `AppStorePurchaseHandler` in `dart-backend/lib/app_store_purchase_handler.dart` to accept `AppStoreServerAPI appStoreServerAPI`, start a 10-second `Timer.periodic` calling `_pullStatus()`, query `appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId)` for active App Store subscriptions in `iapRepository`, and update their expiration date and `SubscriptionStatus` in Firestore.
- Update `dart-backend/bin/server.dart` to add `pubsub.PubsubApi.cloudPlatformScope` to the Google Play client scopes, construct `PubsubApi` and `AppStoreServerAPI` (reading `assets/SubscriptionKey.p8` and caching JWT tokens in `assets/appstore.token`), and pass them to `GooglePlayPurchaseHandler` and `AppStorePurchaseHandler`.
- Create unit tests in `dart-backend/test/firebase_backend_dart_test.dart` verifying `extractOrderId` (with and without a `..0` suffix) and `getPurchaseData` (valid and invalid payloads).

2. In `app/`:
- Update `DashPurchases` in `app/lib/logic/dash_purchases.dart` (and its provider in `app/lib/main.dart`) to accept `this.iapRepo` (`IAPRepo`), register `iapRepo.addListener(purchasesUpdate)` in the constructor and `iapRepo.removeListener(purchasesUpdate)` in `dispose()`, and implement `purchasesUpdate()` and `_updateStatus(PurchasableProduct product, ProductStatus status)` (setting `product.status = status` when `product.status != status`) so `iapRepo.hasActiveSubscription` applies or removes the paid counter multiplier and `iapRepo.hasUpgrade` updates `_beautifiedDashUpgrade` and product statuses.

Understanding the generated code

Polling Google Play Pub/Sub and the App Store Server API on the backend

In dart-backend/lib/google_play_purchase_handler.dart, _pullMessageFromPubSub polls the projects/$googleCloudProjectId/subscriptions/$googlePlayPubsubBillingTopic-sub subscription every 10 seconds, decodes each base64 notification payload, re-runs handleSubscription or handleNonSubscription to refresh Firestore, and acknowledges the message using _ackMessage:

  Future<void> _pullMessageFromPubSub() async {
    print('Polling Google Play messages');
    final request = pubsub.PullRequest(maxMessages: 1000);
    final topicName =
        'projects/$googleCloudProjectId/subscriptions/$googlePlayPubsubBillingTopic-sub';
    final pullResponse = await pubsubApi.projects.subscriptions.pull(
      request,
      topicName,
    );
    final messages = pullResponse.receivedMessages ?? [];
    for (final message in messages) {
      final data64 = message.message?.data;
      if (data64 != null) {
        await _processMessage(data64, message.ackId);
      }
    }
  }

Similarly, in dart-backend/lib/app_store_purchase_handler.dart, _pullStatus queries appStoreServerAPI.getAllSubscriptionStatuses(purchase.orderId) every 10 seconds and updates each subscription's expiryDate and SubscriptionStatus (active or expired) in Cloud Firestore.

Synchronizing Firestore purchases on the device

In app/lib/repo/iap_repo.dart, IAPRepo listens to the authenticated user's purchases documents in Cloud Firestore in real time and computes hasActiveSubscription and hasUpgrade:

    var purchaseStream = _firestore
        .collection('purchases')
        .where('userId', isEqualTo: user.uid)
        .snapshots();
    _purchaseSubscription = purchaseStream.listen((snapshot) {
      purchases = snapshot.docs.map((document) {
        var data = document.data();
        return PastPurchase.fromJson(data);
      }).toList();

      hasActiveSubscription = purchases.any(
        (element) =>
            element.productId == storeKeySubscription &&
            element.status != Status.expired,
      );

      hasUpgrade = purchases.any(
        (element) => element.productId == storeKeyUpgrade,
      );

      notifyListeners();
    });

Whenever IAPRepo notifies its listeners, DashPurchases.purchasesUpdate() in app/lib/logic/dash_purchases.dart enables or disables the 10x click multiplier, toggles _beautifiedDashUpgrade, and updates the product statuses displayed on PurchasePage:

  void purchasesUpdate() {
    var subscriptions = <PurchasableProduct>[];
    var upgrades = <PurchasableProduct>[];
    if (products.isNotEmpty) {
      subscriptions = products
          .where((element) => element.productDetails.id == storeKeySubscription)
          .toList();
      upgrades = products
          .where((element) => element.productDetails.id == storeKeyUpgrade)
          .toList();
    }

    if (iapRepo.hasActiveSubscription) {
      counter.applyPaidMultiplier();
      for (var element in subscriptions) {
        _updateStatus(element, ProductStatus.purchased);
      }
    } else {
      counter.removePaidMultiplier();
      for (var element in subscriptions) {
        _updateStatus(element, ProductStatus.purchasable);
      }
    }

    if (iapRepo.hasUpgrade != _beautifiedDashUpgrade) {
      _beautifiedDashUpgrade = iapRepo.hasUpgrade;
      for (var element in upgrades) {
        _updateStatus(
          element,
          _beautifiedDashUpgrade
              ? ProductStatus.purchased
              : ProductStatus.purchasable,
        );
      }
      notifyListeners();
    }
  }

  void _updateStatus(PurchasableProduct product, ProductStatus status) {
    if (product.status != status) {
      product.status = status;
      notifyListeners();
    }
  }

Run and test the app and backend

Run the unit and widget tests across both projects to verify that everything analyzes and passes cleanly:

cd dart-backend
dart test
cd ../app
flutter test

12. Congratulations

Congratulations! You have collaborated with Google Antigravity to build a full-stack in-app purchase integration in Flutter with a Dart verification backend.

What you've built

  • Configured consumable (dash_consumable_2k), non-consumable (dash_upgrade_3d), and auto-renewing subscription (dash_subscription_doubler) products in App Store Connect and Google Play Console.
  • Connected the Dash Clicker Flutter app (app/) to the in_app_purchase plugin, querying product details and listening to purchaseStream.
  • Built a Dart shelf backend (dart-backend/) that verifies purchase tokens with the Google Play Android Developer API and App Store, polls billing updates using Cloud Pub/Sub and the App Store Server API, and persists purchase state in Cloud Firestore.
  • Synchronized verified purchase entitlements back to the Flutter client in real time using IAPRepo.

Next steps

  • Add Firebase Auth ID token verification middleware to POST /verifypurchase in dart-backend/bin/server.dart.
  • Deploy dart-backend/ to Cloud Run and configure push webhooks for Google Cloud Pub/Sub and App Store Server Notifications.

Learn more