### detectReferrer Example Usage Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md An example demonstrating how to call the `detectReferrer` method and handle the result, printing the installation platform on success or the error on failure. ```kotlin val callback = { result: Result -> if (result.isSuccess) { val referrer = result.getOrNull() println("Platform: ${referrer?.installationPlatform}") } else { println("Error: ${result.exceptionOrNull()}") } } plugin.detectReferrer(callback) ``` -------------------------------- ### Android Setup Flow Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md Example of how to set up the InstallReferrer platform channel API within a Flutter plugin's onAttachedToEngine method. ```kotlin // In InstallReferrerPlugin.onAttachedToEngine() InstallReferrerInternalAPI.setUp( flutterPluginBinding.binaryMessenger, this // this plugin implements InstallReferrerInternalAPI ) ``` -------------------------------- ### Get All Installation Data Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Use `InstallReferrer.app` to retrieve both the package name (or app ID) and the referrer enum. This is useful when you need comprehensive installation information. ```dart final installationApp = await InstallReferrer.app; // Access package name (Android) or app ID (iOS) String? packageName = installationApp.packageName; // Access referrer enum InstallationAppReferrer referrer = installationApp.referrer; ``` -------------------------------- ### Get Complete Application Information Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md Retrieves the package name and installation referrer. Fetches fresh data on each call. Use this when you need both the app identifier and its installation source. ```dart import 'package:flutter_install_referrer/flutter_install_referrer.dart'; void checkInstaller() async { try { final installationApp = await InstallReferrer.app; print('Package: ${installationApp.packageName}'); print('Referrer: ${installationApp.referrer}'); } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Plugin Registration Setup Flow (Swift) Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md Example of how to set up the InstallReferrerInternalAPI within the Flutter plugin's registration method. This connects the native API to the Flutter binary messenger. ```swift // In SwiftInstallReferrerPlugin.register(with:registrar) let api: InstallReferrerInternalAPI & NSObjectProtocol = SwiftInstallReferrerPlugin() InstallReferrerInternalAPISetup.setUp(binaryMessenger: messenger, api: api) ``` -------------------------------- ### InstallationApp Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md Data class wrapping the complete installation detection result. It contains the package name and the installation referrer information. ```APIDOC ## InstallationApp ### Description Data class wrapping the complete installation detection result. It contains the package name and the installation referrer information. ### Fields | Field | Type | Nullable | Description | |-------|------|----------|-------------| | packageName | `String` | Yes | Android package name or iOS app ID. May be `null` in rare cases. | | referrer | `InstallationAppReferrer` | No | Enum indicating the installation source (cannot be null). | ### Usage Returned by `InstallReferrer.app` getter. Used with `InstallReferrerDetectorBuilder` and `InstallReferrerDetectorListener` widgets. ### Example ```dart final app = await InstallReferrer.app; if (app.packageName != null) { print('App ID: ${app.packageName}'); } print('From: ${app.referrer}'); ``` ``` -------------------------------- ### InstallReferrerDetectorBuilder Usage Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md Demonstrates how to use InstallReferrerDetectorBuilder to display installation referrer information. Use this widget when you need to obtain referrer results directly within a widget's build tree. ```dart import 'package:flutter/material.dart'; import 'package:flutter_install_referrer/flutter_install_referrer.dart'; Widget buildApp() { return InstallReferrerDetectorBuilder( builder: (BuildContext context, InstallationApp? app) { if (app == null) { return const CircularProgressIndicator(); } return Column( children: [ Text('Package: ${app.packageName ?? "Unknown"}'), Text('Referrer: ${app.referrer}'), ], ); }, ); } ``` -------------------------------- ### Get Installation Referrer with Caching Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md Detects the installation source and caches the result for subsequent calls. Use this when you primarily need the referrer and want to optimize performance by avoiding repeated native calls. ```dart import 'package:flutter_install_referrer/flutter_install_referrer.dart'; void detectReferrer() async { try { final referrer = await InstallReferrer.referrer; if (referrer == InstallationAppReferrer.androidGooglePlay) { print('Installed from Google Play'); } else if (referrer == InstallationAppReferrer.iosAppStore) { print('Installed from Apple App Store'); } } catch (e) { print('Detection failed: $e'); } } ``` -------------------------------- ### Get Installation Referrer Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/README.md Import the package and invoke the InstallReferrer.referrer Future to get the installation referrer value. ```dart import 'package:flutter_install_referrer/flutter_install_referrer.dart'; Future getReferrer() async { final String? referrer = await InstallReferrer.referrer; print('Installation referrer: $referrer'); } ``` -------------------------------- ### setUp Method Signature Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md The signature for the setUp method, used to register the platform channel listener on the native side. It accepts a BinaryMessenger, an API implementation, and an optional message channel suffix. ```kotlin @JvmOverloads fun setUp( binaryMessenger: BinaryMessenger, api: InstallReferrerInternalAPI?, messageChannelSuffix: String = "" ) ``` -------------------------------- ### setUp() Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md Registers the platform channel listener on the native side, allowing Flutter to communicate with the native implementation. ```APIDOC ## setUp() ### Description Registers the platform channel listener on the native side. ### Signature ```kotlin @JvmOverloads fun setUp( binaryMessenger: BinaryMessenger, api: InstallReferrerInternalAPI?, messageChannelSuffix: String = "" ) ``` ### Parameters - **binaryMessenger** (BinaryMessenger) - Required - Flutter's binary messenger for IPC. - **api** (InstallReferrerInternalAPI?) - Optional - Implementation instance (null to unregister). - **messageChannelSuffix** (String) - Optional - Suffix for multiple channel instances. ``` -------------------------------- ### Debug Display Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Provides a simple example of displaying the referrer information for debugging purposes. ```dart InstallReferrerDetectorBuilder( builder: (context, value) { return Text('Debug Referrer: ${value?.referrer ?? 'N/A'}'); }, ) ``` -------------------------------- ### InstallReferrer Class Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Demonstrates the basic structure of the InstallReferrer class, including its app and referrer properties. ```dart class InstallReferrer { final String app; final String referrer; InstallReferrer({required this.app, required this.referrer}); } ``` -------------------------------- ### InstallationApp Usage Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md Demonstrates how to retrieve and use the InstallationApp object to access package name and referrer information. ```dart final app = await InstallReferrer.app; if (app.packageName != null) { print('App ID: ${app.packageName}'); } print('From: ${app.referrer}'); ``` -------------------------------- ### Convert Installation Source to Readable String Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Provides a human-readable string representation for various installation sources. This is useful for debugging or displaying information to the user. ```dart String referrerToReadableString(InstallationAppReferrer referrer) { switch (referrer) { case InstallationAppReferrer.iosAppStore: return "Apple App Store"; case InstallationAppReferrer.iosTestFlight: return "TestFlight"; case InstallationAppReferrer.iosDebug: return "Debug (Simulator)"; case InstallationAppReferrer.androidGooglePlay: return "Google Play"; case InstallationAppReferrer.androidAmazonAppStore: return "Amazon Appstore"; case InstallationAppReferrer.androidHuaweiAppGallery: return "Huawei AppGallery"; case InstallationAppReferrer.androidOppoAppMarket: return "OPPO App Market"; case InstallationAppReferrer.androidSamsungAppShop: return "Samsung Galaxy Store"; case InstallationAppReferrer.androidVivoAppStore: return "Vivo App Store"; case InstallationAppReferrer.androidXiaomiAppStore: return "Xiaomi App Store"; case InstallationAppReferrer.androidManually: return "Manual Installation"; case InstallationAppReferrer.androidDebug: return "Debug (Android)"; } } // Usage final app = await InstallReferrer.app; debugPrint('Installed from: ${referrerToReadableString(app.referrer)}'); ``` -------------------------------- ### Run flutter pub get Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md After adding the dependency, run `flutter pub get` to fetch the package. ```bash flutter pub get ``` -------------------------------- ### Documentation Structure Overview Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Illustrates the layered structure of the documentation for the Flutter Install Referrer plugin. ```markdown Quick Reference Layer (README.md) ↓ Specialization Layer ├─ usage-guide.md (app developers) ├─ api-reference.md (API consumers) ├─ types.md (type reference) ├─ architecture.md (designers) └─ platform-channel-spec.md (integrators) ↓ Implementation Layer ├─ android-native-api.md (Android implementation) └─ ios-native-api.md (iOS implementation) ``` -------------------------------- ### Flutter Install Referrer Plugin Structure Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/architecture.md This tree view shows the directory structure of the flutter_install_referrer plugin, highlighting the entry point, public and private source directories, Pigeon-generated code, platform-specific implementations, and the example usage. ```tree flutter-install-referrer/ ├── lib/ │ ├── flutter_install_referrer.dart [ENTRY POINT] │ │ └── Exports public API │ │ │ └── src/ │ ├── public/ │ │ ├── plugin.dart [InstallReferrer class] │ │ ├── model.dart [Public types] │ │ └── widget.dart [Widget helpers] │ │ │ └── private/ │ └── pigeon_api.dart [Pigeon-generated code] │ ├── pigeons/ │ └── messages.dart [Pigeon specification] │ ├── android/ │ └── src/main/kotlin/... │ ├── InstallReferrerPlugin.kt [Android implementation] │ └── InstallReferrerPigeon.kt [Pigeon-generated] │ ├── ios/ │ └── Sources/flutter_install_referrer/ │ ├── SwiftInstallReferrerPlugin.swift [iOS implementation] │ └── SwiftInstallReferrerPigeon.swift [Pigeon-generated] │ └── example/ └── lib/main.dart [Usage example] ``` -------------------------------- ### InstallReferrerDetectorListener Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md A StatefulWidget that provides installation referrer detection results via a listener callback. It fetches the installation app information once during initState() and invokes the provided callback with the result. ```APIDOC ## InstallReferrerDetectorListener ### Description StatefulWidget wrapper that provides installation referrer detection results via a listener callback. ### Constructor ```dart const InstallReferrerDetectorListener({ required Widget child, required InstallReferrerDetectorWidgetListener onReferrerAvailable, Key? key, }) ``` ### Parameters #### Constructor Parameters - **child** (`Widget`) - Required - Child widget to render below this listener - **onReferrerAvailable** (`InstallReferrerDetectorWidgetListener`) - Required - Callback invoked when installation app data is available - **key** (`Key?`) - Optional - Widget key for Flutter widget tree ### Behavior This widget fetches the installation app information once during `initState()`. The `onReferrerAvailable` callback is invoked with the result. If the callback is updated via `didUpdateWidget()`, the referrer is re-fetched and the new callback is invoked. ### Example ```dart import 'package:flutter/material.dart'; import 'package:flutter_install_referrer/flutter_install_referrer.dart'; Widget buildWithListener() { return InstallReferrerDetectorListener( onReferrerAvailable: (InstallationApp app) { print('Detected: ${app.referrer}'); // Log to analytics or perform other side effects }, child: Scaffold( appBar: AppBar(title: const Text('My App')), body: const Center(child: Text('Content here')), ), ); } ``` ``` -------------------------------- ### Timeouts Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Shows how to implement timeouts for the referrer detection process. ```dart InstallReferrerDetectorBuilder( timeout: Duration(seconds: 5), builder: (context, value) { // Handle timeout scenario if value is null after 5 seconds return Text('Referrer: ${value?.referrer ?? 'N/A'}'); }, ) ``` -------------------------------- ### Pigeon Configuration Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Shows a basic Pigeon configuration, specifying input and output file locations. ```yaml plugins: pigeon: input_dir: "pigeons" output_dir: "lib/generated" # ... other configurations ... ``` -------------------------------- ### Example IRInstallationReferrer Serialization Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md Demonstrates the byte-level serialization of an IRInstallationReferrer object, showing the type codes and content for each field. ```text [132, // IRInstallationReferrer type code [ [129, 2], // type: IRInstallationType.debug (index 2) [130, 2], // installationPlatform: IRInstallationPlatform.googlePlay (index 2) [131, 1], // platform: IRPlatform.android (index 1) "com.example" // packageName: String ] ] ``` -------------------------------- ### InstallationAppReferrer Usage Pattern Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md Illustrates how to use a switch statement with the InstallationAppReferrer enum to handle different installation sources. ```dart final referrer = await InstallReferrer.referrer; switch (referrer) { case InstallationAppReferrer.androidGooglePlay: // App from Google Play break; case InstallationAppReferrer.iosAppStore: // App from Apple App Store break; case InstallationAppReferrer.androidDebug || InstallationAppReferrer.iosDebug: // Debug build break; default: // Other stores } ``` -------------------------------- ### InstallReferrer API Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/README.md Provides static methods to access installation and referrer data. ```APIDOC ## Class InstallReferrer ### Description Primary API class for retrieving installation and referrer information. ### Methods #### `static Future get app` - **Description**: Retrieves detailed information about the installed application. - **Returns**: A `Future` that resolves to an `InstallationApp` object. #### `static Future get referrer` - **Description**: Retrieves the referrer information for the application installation. - **Returns**: A `Future` that resolves to an `InstallationAppReferrer` enum value. ``` -------------------------------- ### Local Storage Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Illustrates saving the referrer information to local storage for later use. ```dart InstallReferrerDetectorBuilder( builder: (context, value) { if (value?.referrer != null) { LocalStorageService.saveReferrer(value!.referrer); } return Container(); }, ) ``` -------------------------------- ### Flutter Install Referrer Public API Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/README.md Use these classes to retrieve installation and referrer information within your Flutter application. Ensure the plugin is properly initialized. ```dart class InstallReferrer { static Future get app; static Future get referrer; } class InstallationApp { final String? packageName; final InstallationAppReferrer referrer; } class InstallReferrerDetectorBuilder extends StatelessWidget { } class InstallReferrerDetectorListener extends StatefulWidget { } enum InstallationAppReferrer { iosAppStore, iosTestFlight, iosDebug, androidGooglePlay, androidAmazonAppStore, androidHuaweiAppGallery, androidOppoAppMarket, androidSamsungAppShop, androidVivoAppStore, androidXiaomiAppStore, androidManually, androidDebug, } ``` -------------------------------- ### Install Referrer Channel Name Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md The specific channel name used for detecting the install referrer. An optional suffix can be appended. ```text dev.flutter.pigeon.flutter_install_referrer.InstallReferrerInternalAPI.detectReferrer ``` -------------------------------- ### Install Referrer Success Response Format Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md The expected format for a successful response from the native platform, containing an IRInstallationReferrer object. ```text [IRInstallationReferrer] ``` -------------------------------- ### Android Installer Package Name Detection Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Details the logic for detecting the installer package name across 7 different stores on Android. ```kotlin private fun getInstallerPackageName(context: Context): String? { val installer = context.packageManager.getInstallerPackageName(packageName) return when (installer) { "com.android.vending" -> "Google Play Store" "com.amazon.venezia" -> "Amazon Appstore" // ... other store package names ... else -> installer } } ``` -------------------------------- ### Analytics Integration Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Demonstrates how to integrate the plugin's data with an analytics service. ```dart InstallReferrerDetectorBuilder( builder: (context, value) { if (value?.referrer != null) { AnalyticsService.logEvent('install_referrer', {'referrer': value!.referrer}); } return Text('Referrer: ${value?.referrer ?? 'N/A'}'); }, ) ``` -------------------------------- ### InstallationAppReferrer Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md Enumeration representing the application or store that installed the current app. It distinguishes between various app stores and installation contexts for both iOS and Android. ```APIDOC ## InstallationAppReferrer ### Description Enumeration representing the application or store that installed the current app. It distinguishes between various app stores and installation contexts for both iOS and Android. ### Enum Values #### iOS Values | Value | Meaning | Condition | |-------|---------|-----------| | `iosAppStore` | Apple App Store | App signed with production certificate and App Store receipt present | | `iosTestFlight` | TestFlight beta testing | App has sandbox receipt (TestFlight marker) | | `iosDebug` | Debug/Simulator mode | Debug build or running on simulator | #### Android Values | Value | Meaning | Condition | |-------|---------|-----------| | `androidGooglePlay` | Google Play Store | `packageManager.getInstallerPackageName()` returns `com.android.vending` | | `androidAmazonAppStore` | Amazon Appstore | `packageManager.getInstallerPackageName()` returns `com.amazon` | | `androidHuaweiAppGallery` | Huawei AppGallery / HarmonyOS | `packageManager.getInstallerPackageName()` returns `com.huawei.appmarket` | | `androidOppoAppMarket` | OPPO App Market | `packageManager.getInstallerPackageName()` returns `com.oppo.market` | | `androidSamsungAppShop` | Samsung Galaxy Store | `packageManager.getInstallerPackageName()` returns `com.sec.android.app.samsungapps` | | `androidVivoAppStore` | Vivo App Store | `packageManager.getInstallerPackageName()` returns `com.vivo.appstore` | | `androidXiaomiAppStore` | Xiaomi App Store | `packageManager.getInstallerPackageName()` returns `com.xiaomi.mipicks` | | `androidManually` | Manual/Sideloaded installation | App installed from non-store source (Chrome, Gmail, etc.) or from non-system store app | | `androidDebug` | Debug mode | Unknown installer package or no installer detected | ### Usage Patterns ```dart final referrer = await InstallReferrer.referrer; switch (referrer) { case InstallationAppReferrer.androidGooglePlay: // App from Google Play break; case InstallationAppReferrer.iosAppStore: // App from Apple App Store break; case InstallationAppReferrer.androidDebug || InstallationAppReferrer.iosDebug: // Debug build break; default: // Other stores } ``` ``` -------------------------------- ### InstallationApp Class Definition Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md Defines the structure for holding installation detection results, including the app's package name and its referrer. ```dart class InstallationApp { final String? packageName; final InstallationAppReferrer referrer; InstallationApp({ required this.packageName, required this.referrer, }); } ``` -------------------------------- ### Error Handling Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Demonstrates how to handle potential errors during referrer detection. ```dart InstallReferrerDetectorBuilder( builder: (context, value) { if (value?.error != null) { // Handle error, e.g., show an error message return Text('Error detecting referrer: ${value!.error}'); } return Text('Referrer: ${value?.referrer ?? 'N/A'}'); }, ) ``` -------------------------------- ### InstallationApp Data Model Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/README.md Represents the data model for an installed application. ```APIDOC ## Class InstallationApp ### Description Data model representing an installed application and its associated referrer information. ### Fields - **packageName** (String?) - The package name of the application. - **referrer** (InstallationAppReferrer) - The referrer information associated with the installation. ``` -------------------------------- ### Log Installation Source to Firebase Analytics Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Log the app's installation source and package name to Firebase Analytics. Ensure Firebase Analytics is set up in your project. ```dart import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:flutter_install_referrer/flutter_install_referrer.dart'; Future logInstallationSource() async { try { final app = await InstallReferrer.app; FirebaseAnalytics.instance.logEvent( name: 'app_installation', parameters: { 'package_name': app.packageName, 'referrer': app.referrer.toString(), }, ); } catch (e) { print('Analytics logging failed: $e'); } } ``` -------------------------------- ### Persist Installation Source in Local Storage Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Store the installation source and package name in local preferences using shared_preferences. This requires the shared_preferences package to be added to your project. ```dart import 'package:shared_preferences/shared_preferences.dart'; Future persistInstallationSource() async { try { final app = await InstallReferrer.app; final prefs = await SharedPreferences.getInstance(); await prefs.setString('installation_source', app.referrer.toString()); if (app.packageName != null) { await prefs.setString('app_package_name', app.packageName!); } } catch (e) { print('Failed to persist installation source: $e'); } } ``` -------------------------------- ### Feature Flags Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Shows how to use the referrer information to conditionally enable features. ```dart InstallReferrerDetectorBuilder( builder: (context, value) { bool showSpecialOffer = value?.referrer == 'special_campaign'; return showSpecialOffer ? SpecialOfferWidget() : NormalWidget(); }, ) ``` -------------------------------- ### InstallationAppReferrer Enum Definition Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md Enumerates the possible sources of app installation, covering various app stores and installation methods for both iOS and Android. ```dart enum InstallationAppReferrer { // iOS iosAppStore, iosTestFlight, iosDebug, // Android androidGooglePlay, androidAmazonAppStore, androidHuaweiAppGallery, androidOppoAppMarket, androidSamsungAppShop, androidVivoAppStore, androidXiaomiAppStore, androidManually, androidDebug, } ``` -------------------------------- ### Swift - detectReferrer() Implementation Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md This function detects the app's installation source (App Store, TestFlight, or debug) and returns the result via a completion handler. It adjusts the referrer type and installation platform based on build configurations. ```swift func detectReferrer(completion: @escaping (Result) -> Void) { // 1. Create base referrer with App Store defaults var installationReferrer = IRInstallationReferrer( type: .appStore, installationPlatform: .appleAppStore, platform: .ios, packageName: Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String ) // 2. Adjust if debug build if isDebug { installationReferrer.type = .debug installationReferrer.installationPlatform = .manually } // 3. Adjust if TestFlight else if isFromTestFlight { installationReferrer.type = .test installationReferrer.installationPlatform = .appleTestflight } // 4. Return result synchronously completion(.success(installationReferrer)) } ``` -------------------------------- ### Detecting Installation Referrer Data Flow Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/architecture.md This sequence diagram illustrates the data flow for detecting an installation referrer, from the user initiating the detection in Dart to the native platform performing the detection and returning the result. ```sequence 1. USER INITIATES DETECTION ↓ var referrer = await InstallReferrer.referrer; 2. DART LAYER (lib/src/public/plugin.dart) ↓ InstallReferrer.referrer getter ├─ Check cache: _cachedReferrer != null? │ └─ Yes: Return cached value immediately │ └─ No: Continue ├─ Call _api.detectReferrer() └─ Wait for result 3. PIGEON BINARY CHANNEL (Auto-generated) ├─ Dart side serializes call ├─ Serializes to binary message └─ Sends message via BinaryMessenger 4. NATIVE SIDE RECEIVES MESSAGE ├─ Pigeon codec deserializes ├─ Routes to registered handler └─ Calls detectReferrer(callback) 5. PLATFORM-SPECIFIC DETECTION ├─ Android: │ ├─ context.packageManager.getInstallerPackageName() │ ├─ Match against known package names │ └─ Create IRInstallationReferrer │ └─ iOS: ├─ Check DEBUG flag (isDebug) ├─ Check sandbox receipt (isFromTestFlight) ├─ Extract CFBundleIdentifier └─ Create IRInstallationReferrer 6. NATIVE RETURNS RESULT ├─ Invoke callback with Result.success() ├─ Pigeon codec serializes response ├─ Sends binary message back └─ Dart receives and deserializes 7. DART PROCESSES RESULT ├─ Receive IRInstallationReferrer (internal type) ├─ Call _extractReferrer() to map to public enum ├─ Cache result in _cachedReferrer └─ Return InstallationAppReferrer to user 8. USER RECEIVES RESULT ↓ referrer == InstallationAppReferrer.androidGooglePlay (or similar) ``` -------------------------------- ### Mocking Strategy Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Illustrates a basic strategy for mocking the referrer detection during testing. ```dart // In your test file: await tester.pumpWidget( MaterialApp( home: InstallReferrerDetectorBuilder( // Provide mock value for testing initialValue: InstallReferrerDetectorValue(app: 'mock_app', referrer: 'mock_referrer'), builder: (context, value) => Text('Test Referrer: ${value?.referrer}'), ), ), ); expect(find.text('Test Referrer: mock_referrer'), findsOneWidget); ``` -------------------------------- ### InstallReferrer Class Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Provides access to installation details, including the application name and referrer information. It exposes properties to retrieve this data. ```APIDOC ## InstallReferrer Class ### Description Provides access to installation details, including the application name and referrer information. It exposes properties to retrieve this data. ### Properties - **app** (getter) - The name of the application. - **referrer** (getter) - The referrer information for the installation. ### Private Methods - **_extractReferrer** - **_iOSReferrer** - **_androidReferrer** ``` -------------------------------- ### InstallReferrer.app Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md Retrieves complete application information including package/app name and installation referrer. This is an asynchronous getter that queries the native platform layer to detect the application installer source. ```APIDOC ## InstallReferrer.app ### Description Retrieves complete application information including package/app name and installation referrer. Asynchronous getter that queries the native platform layer to detect the application installer source. Returns an `InstallationApp` object containing both the package/app ID and the installation referrer enum value. ### Method GET ### Endpoint `/app` ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **packageName** (String?) - The Android package name or iOS app ID - **referrer** (InstallationAppReferrer) - An enum indicating the installation source #### Response Example { "packageName": "com.example.app", "referrer": "androidGooglePlay" } ### Throws - `UnsupportedError` if called on an unsupported platform ``` -------------------------------- ### InstallReferrer.referrer Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md Detects which application or store installed the current application, with automatic caching. This is an asynchronous getter that returns only the installation referrer enum value, and the result is cached internally after the first successful call. ```APIDOC ## InstallReferrer.referrer ### Description Detects which application or store installed the current application, with automatic caching. Asynchronous getter that returns only the installation referrer enum value. The result is cached internally after the first successful call, so subsequent invocations return the cached value without querying the native layer. ### Method GET ### Endpoint `/referrer` ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **referrer** (InstallationAppReferrer) - An enum value representing the installation source #### Response Example { "referrer": "androidGooglePlay" } ### Throws - `UnsupportedError` if called on an unsupported platform ``` -------------------------------- ### InstallationAppReferrer Enum Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/README.md Enum representing the different types of install referrers. ```APIDOC ## Enum InstallationAppReferrer ### Description Enumerates the possible sources of the app installation referrer. ### Values - **iosAppStore** - **iosTestFlight** - **iosDebug** - **androidGooglePlay** - **androidAmazonAppStore** - **androidHuaweiAppGallery** - **androidOppoAppMarket** - **androidSamsungAppShop** - **androidVivoAppStore** - **androidXiaomiAppStore** - **androidManually** - **androidDebug** ``` -------------------------------- ### InstallReferrerDetector Widgets Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/README.md Widget helpers for detecting install referrer information. ```APIDOC ## Widget InstallReferrerDetectorBuilder ### Description A widget builder for detecting install referrer information. ## Widget InstallReferrerDetectorListener ### Description A stateful widget for listening to install referrer information. ``` -------------------------------- ### iOS Detection Method Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Details the methods for detecting install referrer information on iOS based on the source. ```markdown | Source | Method | |--------|--------| | App Store | Production receipt | | TestFlight | Sandbox receipt detection | | Debug | DEBUG compilation flag | ``` -------------------------------- ### Public InstallationApp Data Class Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/architecture.md Defines the user-facing data class for installation app details, including its referrer type. ```dart InstallationApp (data class) ├─ packageName: String? └─ referrer: InstallationAppReferrer ``` -------------------------------- ### Android Installer Package Names Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/INDEX.md Lists the package names for various Android app stores used for referrer detection. ```markdown | Store | Package | |-------|---------| | Google Play | `com.android.vending` | | Amazon | `com.amazon` | | Huawei | `com.huawei.appmarket` | | OPPO | `com.oppo.market` | | Samsung | `com.sec.android.app.samsungapps` | | Vivo | `com.vivo.appstore` | | Xiaomi | `com.xiaomi.mipicks` | ``` -------------------------------- ### Install Referrer Error Response Format Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md The format for an error response from the native platform, including error code, message, and details. ```text [errorCode: String, errorMessage: String?, errorDetails: Any?] ``` -------------------------------- ### detectReferrer() Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md Platform channel method for detecting the installation referrer. It invokes the native implementation and returns the result via a callback. ```APIDOC ## detectReferrer() ### Description Platform channel method for referrer detection. ### Parameters #### Callback - `callback` (Result) - Required - Called with the result of the referrer detection, which can be a success or an error. ``` -------------------------------- ### Get Only the Referrer Source Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Use `InstallReferrer.referrer` when you only need to know the source of the installation. This snippet shows how to check if the app was installed from the Google Play Store. ```dart final referrer = await InstallReferrer.referrer; if (referrer == InstallationAppReferrer.androidGooglePlay) { print('Installed from Google Play'); } ``` -------------------------------- ### InstallReferrerInternalAPISetup setUp() Method Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md Registers the platform channel handler for referrer detection on the native iOS side. Pass an implementation of InstallReferrerInternalAPI to handle requests from Flutter. ```swift static func setUp( binaryMessenger: FlutterBinaryMessenger, api: InstallReferrerInternalAPI?, messageChannelSuffix: String = "" ) ``` -------------------------------- ### Log Installation Source for Support Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Log the referrer and package name to assist your support team in diagnosing installation-related issues. This data can be crucial for understanding user acquisition channels. ```dart void setupLogging() async { final app = await InstallReferrer.app; logger.info( 'App installation detected', extra: { 'referrer': app.referrer, 'package': app.packageName, }, ); } ``` -------------------------------- ### InstallReferrerInternalAPISetup.setUp Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md This class provides static methods for setting up the Pigeon-generated platform channel for the InstallReferrerInternalAPI on iOS. It handles the registration of the message channel and the binding of the API implementation. ```APIDOC ## setUp() ### Description Registers the platform channel handler on the native side. ### Method `static func setUp( binaryMessenger: FlutterBinaryMessenger, api: InstallReferrerInternalAPI?, messageChannelSuffix: String = "" )` ### Parameters - `binaryMessenger` (FlutterBinaryMessenger) - Required - Flutter's binary messenger for IPC. - `api` (InstallReferrerInternalAPI?) - Optional - Implementation instance (nil to unregister). - `messageChannelSuffix` (String) - Optional - Suffix for multiple channel instances. ### Implementation Details 1. Constructs channel name suffix: `.{messageChannelSuffix}` if provided, empty otherwise. 2. Creates a `FlutterBasicMessageChannel` with name: `dev.flutter.pigeon.flutter_install_referrer.InstallReferrerInternalAPI.detectReferrer{suffix}`. 3. Sets message handler (if api is not nil): Calls `api.detectReferrer { result in ... }`, wrapping success with `wrapResult(res)` and failure with `wrapError(error)`. 4. Clears message handler if api is nil (for cleanup). ``` -------------------------------- ### Get Referrer with Timeout in Flutter Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md This function attempts to retrieve the install referrer within a specified timeout period. It returns null if a timeout occurs or if any other error is encountered during detection. ```dart Future getReferrerWithTimeout({ Duration timeout = const Duration(seconds: 5), }) async { try { return await InstallReferrer.referrer.timeout(timeout); } on TimeoutException { print('Referrer detection timed out'); return null; } catch (e) { print('Error: $e'); return null; } } ``` -------------------------------- ### Detect Installation Source with Dart Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/README.md Use this snippet to asynchronously retrieve the installation referrer. It checks if the app was installed from the Google Play Store. ```dart final referrer = await InstallReferrer.referrer; if (referrer == InstallationAppReferrer.androidGooglePlay) { // Installed from Google Play } ``` -------------------------------- ### InstallReferrerPlugin.detectReferrer Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md Detects the application installer package and maps it to the appropriate store/installation type. It uses Android's PackageManager to identify the installer and returns the installation platform and type. ```APIDOC ## InstallReferrerPlugin.detectReferrer ### Description Detects the application installer package and maps it to the appropriate store/installation type. ### Method ```kotlin override fun detectReferrer(callback: (Result) -> Unit) ``` ### Parameters #### Path Parameters - `callback` (Result) - Required - success contains referrer data, failure contains exception ### Response #### Success Response - `installationPlatform` (string) - The detected store or installation platform. - `type` (string) - The type of installation (e.g., appStore, debug, unknown, manually). - `packageName` (string) - The package name of the current application. - `platform` (string) - Always 'ANDROID' for this platform. ### Request Example ```kotlin val callback = { result: Result -> if (result.isSuccess) { val referrer = result.getOrNull() println("Platform: ${referrer?.installationPlatform}") } else { println("Error: ${result.exceptionOrNull()}") } } plugin.detectReferrer(callback) ``` ``` -------------------------------- ### IRInstallationType Enum Definition Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md Pigeon-generated Swift enum for classifying installation types. Use these cases to determine how an app was installed. ```swift enum IRInstallationType: Int { case appStore = 0 case test = 1 case debug = 2 case unknown = 3 } ``` -------------------------------- ### detectReferrer Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/platform-channel-spec.md Detects the referrer information for the current app installation. This method requires no arguments and returns either installation referrer details or error information. ```APIDOC ## detectReferrer ### Description Detects the referrer information for the current app installation. This method requires no arguments and returns either installation referrer details or error information. ### Method N/A (Platform Channel Method) ### Endpoint dev.flutter.pigeon.flutter_install_referrer.InstallReferrerInternalAPI.detectReferrer ### Parameters No arguments required. ### Request Example ```json null ``` ### Response #### Success Response - **[IRInstallationReferrer]** (Array) - A list containing a single `IRInstallationReferrer` object. #### Response Example ```json [ { "type": "appStore" | "test" | "debug" | "unknown", "installationPlatform": "appleAppStore" | "appleTestflight" | "googlePlay" | "amazonAppStore" | "huaweiAppGallery" | "oppoAppMarket" | "samsungAppShop" | "vivoAppStore" | "xiaomiAppStore" | "manually" | "unknown", "platform": "ios" | "android", "packageName": "string" } ] ``` #### Error Response - **[errorCode: String, errorMessage: String?, errorDetails: Any?]** (Array) - A list containing error information. #### Error Response Example ```json [ "errorCodeString", "errorMessageString", null ] ``` ``` -------------------------------- ### Direct Access with Caching Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Use `InstallReferrer.referrer` for programmatic access with explicit caching. This pattern provides explicit control and leverages built-in caching, but requires manual error handling. ```dart import 'package:flutter_install_referrer/flutter_install_referrer.dart'; class AppStartup { static Future initialize() async { try { // This caches the result internally final referrer = await InstallReferrer.referrer; print('Installation source: $referrer'); // Subsequent calls return cached value final referrer2 = await InstallReferrer.referrer; // referrer2 == referrer (same instance from cache) } catch (e) { print('Failed to detect referrer: $e'); } } } ``` -------------------------------- ### detectReferrer Method Signature Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md The signature for the core method that detects the application installer package and maps it to the appropriate store or installation type. It uses a callback to return the result. ```kotlin override fun detectReferrer(callback: (Result) -> Unit) ``` -------------------------------- ### Enable Features Based on Installation Source Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/usage-guide.md Determine whether to show a special offer based on whether the app was installed from the iOS App Store or Google Play Store. ```dart Future shouldShowSpecialOffer() async { try { final referrer = await InstallReferrer.referrer; // Show special offer only for App Store and Play Store return referrer == InstallationAppReferrer.iosAppStore || referrer == InstallationAppReferrer.androidGooglePlay; } catch (e) { return false; } } ``` -------------------------------- ### IRInstallationReferrer Data Class Definition Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md A Pigeon-generated data class for serializing installation referrer information on Android. It includes fields for installation type, store, platform, and package name. ```kotlin data class IRInstallationReferrer( val type: IRInstallationType? = null, val installationPlatform: IRInstallationPlatform? = null, val platform: IRPlatform? = null, val packageName: String? = null ) ``` -------------------------------- ### Install Referrer API Type Diagram Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/types.md This diagram illustrates the relationships between the public InstallReferrer API, internal APIs, and user-facing types like InstallationAppReferrer and InstallationApp. It shows how data flows from detection to the public model. ```text ┌─────────────────────────────────────────┐ │ InstallReferrer (public API) │ ├─────────────────────────────────────────┤ │ - app: Future │ │ - referrer: Future │ - _cachedReferrer: InstallationAppReferrer? └──────────────────┬──────────────────────┘ │ uses ▼ ┌─────────────────────────────────┐ │ InstallReferrerInternalAPI │ │ (platform channel) │ └──────────────────┬──────────────┘ │ calls ▼ ┌──────────────────────────┐ │ detectReferrer() │ │ returns IRInstallationReferrer └──────────────────────────┘ │ │ maps to ▼ ┌────────────────────────────────┐ │ InstallationAppReferrer enum │ │ (public user-facing type) │ └────────────────────────────────┘ ┌─────────────────────────────────────┐ │ InstallationApp (public model) │ ├─────────────────────────────────────┤ │ - packageName: String? │ │ - referrer: InstallationAppReferrer │ └─────────────────────────────────────┘ ``` -------------------------------- ### InstallReferrerInternalAPI.detectReferrer Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md This method is part of the Pigeon-generated protocol for iOS. Implementations must provide this method to handle requests for detecting the installation referrer. It returns a Result containing either the installation referrer information or an error. ```APIDOC ## detectReferrer() ### Description Method that implementations must provide to handle referrer detection requests. ### Protocol Methods #### detectReferrer ### Parameters None ### Response - `Result`: A result object that is either success with `IRInstallationReferrer` or failure with an `Error`. ``` -------------------------------- ### TestFlight Installation Detection (Swift) Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md A file-level private constant that detects if the app was installed via TestFlight. It checks the app store receipt URL for the presence of 'sandboxReceipt'. This check is performed once when the module is loaded. ```swift private let isFromTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" ``` -------------------------------- ### InstallReferrerDetectorListener Usage Example Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/api-reference.md Shows how to use InstallReferrerDetectorListener to receive referrer data via a callback. This widget fetches data once in initState and re-fetches if didUpdateWidget is called. ```dart import 'package:flutter/material.dart'; import 'package:flutter_install_referrer/flutter_install_referrer.dart'; Widget buildWithListener() { return InstallReferrerDetectorListener( onReferrerAvailable: (InstallationApp app) { print('Detected: ${app.referrer}'); // Log to analytics or perform other side effects }, child: Scaffold( appBar: AppBar(title: const Text('My App')), body: const Center(child: Text('Content here')), ), ); } ``` -------------------------------- ### IRInstallationReferrer toList Method Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/android-native-api.md Serializes the IRInstallationReferrer instance into a list of Any?. This method is essential for method channel communication using the Pigeon codec. ```kotlin fun toList(): List { return listOf(type, installationPlatform, platform, packageName) } ``` -------------------------------- ### InstallReferrerInternalAPISetup Class Definition Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/ios-native-api.md Pigeon-generated setup class for registering platform channel handlers on iOS. Use this class to bind the native API implementation to the Flutter channel. ```swift class InstallReferrerInternalAPISetup { static var codec: FlutterStandardMessageCodec { SwiftInstallReferrerPigeonPigeonCodec.shared } static func setUp( binaryMessenger: FlutterBinaryMessenger, api: InstallReferrerInternalAPI?, messageChannelSuffix: String = "" ) } ``` -------------------------------- ### Mapping Logic from IRInstallationReferrer to Public Types Source: https://github.com/all-win-solutions/flutter-install-referrer/blob/main/_autodocs/architecture.md Illustrates the logic for mapping internal IRInstallationReferrer details to the public InstallationAppReferrer enum, handling platform-specific conversions and error cases. ```dart _extractReferrer(IRInstallationReferrer) ├─ platform == IRPlatform.ios? │ ├─ _iOSReferrer(installationPlatform) │ │ ├─ appleAppStore → iosAppStore │ │ ├─ appleTestflight → iosTestFlight │ │ └─ other → iosDebug │ │ │ └─ _androidReferrer(installationPlatform, type) │ ├─ googlePlay → androidGooglePlay │ ├─ amazonAppStore → androidAmazonAppStore │ ├─ huaweiAppGallery → androidHuaweiAppGallery │ ├─ oppoAppMarket → androidOppoAppMarket │ ├─ samsungAppShop → androidSamsungAppShop │ ├─ vivoAppStore → androidVivoAppStore │ ├─ xiaomiAppStore → androidXiaomiAppStore │ ├─ manually: │ │ ├─ type == debug → androidDebug │ │ └─ type != debug → androidManually │ ├─ unknown → androidDebug │ └─ default → throw UnimplementedError │ └─ default → throw UnsupportedError ```