{"id":30312717,"url":"https://github.com/mparticle/mparticle-flutter-sdk","last_synced_at":"2025-08-17T17:14:23.909Z","repository":{"id":40996631,"uuid":"399514692","full_name":"mParticle/mparticle-flutter-sdk","owner":"mParticle","description":"A Flutter plugin that gives developers an API to implement mParticle on Flutter.  This supports publishing a Flutter plugin to iOS, Android, and Web.","archived":false,"fork":false,"pushed_at":"2025-06-23T08:03:08.000Z","size":218,"stargazers_count":4,"open_issues_count":5,"forks_count":10,"subscribers_count":6,"default_branch":"development","last_synced_at":"2025-06-23T08:34:28.201Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mParticle.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-08-24T15:22:49.000Z","updated_at":"2025-06-17T02:19:09.000Z","dependencies_parsed_at":"2025-06-14T02:25:28.287Z","dependency_job_id":"cda345dc-8666-4758-832c-392386d7b6ed","html_url":"https://github.com/mParticle/mparticle-flutter-sdk","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/mParticle/mparticle-flutter-sdk","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mParticle%2Fmparticle-flutter-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mParticle%2Fmparticle-flutter-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mParticle%2Fmparticle-flutter-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mParticle%2Fmparticle-flutter-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mParticle","download_url":"https://codeload.github.com/mParticle/mparticle-flutter-sdk/tar.gz/refs/heads/development","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mParticle%2Fmparticle-flutter-sdk/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270877422,"owners_count":24661139,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-17T02:00:09.016Z","response_time":129,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-08-17T17:14:22.532Z","updated_at":"2025-08-17T17:14:23.888Z","avatar_url":"https://github.com/mParticle.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# mparticle_flutter_sdk\n\nFlutter allows developers to use a single code base to deploy to multiple platforms.  Now, with the mParticle Flutter Plugin, you can leverage a single API to deploy your data to hundreds of integrations from your iOS, Android, and Web apps.\n\nSee the table below to see what features are currently supported\n\n### Supported Features\n| Method | Android | iOS | Web | Notes |\n|---|---|---|---| --- |\n| Custom Events | X | X | X |  |\n| Page Views | X | X | X |  |\n| Identity | X | X | X |  |\n| eCommerce | X | X | X |  |\n| Consent | X | X | X |  |\n\n## Installation\n\n1. Add the Flutter SDK as a dependency to your Flutter application:\n\n```bash\nflutter pub add mparticle_flutter_sdk\n```\n\nSpecifying this dependency adds a line like the following to your package's `pubspec.yaml`:\n\n```bash\ndependencies:\n    mparticle_flutter_sdk: ^0.0.1\n```\n\n2.  Import the package into your Dart code:\n\n```bash\nimport 'package:mparticle_flutter_sdk/mparticle_flutter_sdk.dart'\n```\n\nNow that you have the mParticle Dart plugin, install mParticle on your native/web platforms.  Be sure to include an API Key and Secret where required or you will see errors in your logs when launching your app.\n\n### \u003ca name=\"Android\"\u003e\u003c/a\u003eAndroid\n\nTo install mParticle on an Android platform:\n\n1. Add the following dependencies to your app's `build.gradle`:\n\n```groovy\ndependencies {\n    implementation 'com.mparticle:android-core:5+'\n\n    // Required for gathering Android Advertising ID (see below)\n    implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'\n\n    // Recommended to query the Google Play install referrer\n    implementation 'com.android.installreferrer:installreferrer:1.0'\n}\n```\n\n2. Grab your mParticle key and secret from [your workspace's dashboard](https://app.mparticle.com/setup/inputs/apps) and construct an `MParticleOptions` object.\n\n3. Call `start` from the `onCreate` method of your app's `Application` class. It's crucial that the SDK be started here for proper session management. If you don't already have an `Application` class, create it and then specify its fully-qualified name in the `\u003capplication\u003e` tag of your app's `AndroidManifest.xml`.\n\n```java\npackage com.example.myapp;\n\nimport android.app.Application;\nimport com.mparticle.MParticle;\n\npublic class MyApplication extends Application {\n    @Override\n    public void onCreate() {\n        super.onCreate();\n        MParticleOptions options = MParticleOptions.builder(this)\n            .credentials(\"REPLACE ME WITH KEY\",\"REPLACE ME WITH SECRET\")\n            .setLogLevel(MParticle.LogLevel.VERBOSE)\n            .identify(identifyRequest)\n            .identifyTask(\n                new BaseIdentityTask()\n                        .addFailureListener(this)\n                        .addSuccessListener(this)\n                    )\n            .attributionListener(this)\n            .build();\n\n        MParticle.start(options);\n    }\n}\n```\n\n```kotlin\nimport com.mparticle.MParticle\nimport com.mparticle.MParticleOptions\n\nclass ExampleApplication : Application() {\n    override fun onCreate() {\n        super.onCreate()\n        val options = MParticleOptions.builder(this)\n            .credentials(\"REPLACE ME WITH KEY\", \"REPLACE ME WITH SECRET\")\n            .build()\n        MParticle.start(options)\n    }\n}\n```\n\n\u003e **Warning:** Don't log events in your `Application.onCreate()`. Android may instantiate your `Application` class for a lot of reasons, in the background, while the user isn't even using their device. \nFor more help, see [the Android set up docs](https://docs.mparticle.com/developers/sdk/android/getting-started/#create-an-input).\n\n### \u003ca name=\"iOS\"\u003e\u003c/a\u003eiOS\n\nConfiguring iOS:\n\nTo install mParticle on an iOS platform:\n\n\n1. Copy your mParticle key and secret** from [your app's dashboard][1].\n\n[1]: https://app.mparticle.com/apps\n\n2. Install the SDK using CocoaPods:\n\n```bash\n$ # Update your Podfile to depend on 'mParticle-Apple-SDK' version 8.5.0 or later\n$ pod install\n```\n\nThe mParticle SDK is initialized by calling the `startWithOptions` method within the `application:didFinishLaunchingWithOptions:` delegate call. Preferably the location of the initialization method call should be one of the last statements in the `application:didFinishLaunchingWithOptions:`. The `startWithOptions` method requires an options argument containing your key and secret and an initial Identity request.\n\n\u003e Note that you must initialize the SDK in the `application:didFinishLaunchingWithOptions:` method. Other parts of the SDK rely on the `UIApplicationDidBecomeActiveNotification` notification to function properly. Failing to start the SDK as indicated will impair it. Also, please do **not** use _GCD_'s `dispatch_async` to start the SDK.\nFor more help, see [the full iOS set up docs](https://docs.mparticle.com/developers/sdk/ios/getting-started/#create-an-input).\n\n3. Import and start the mParticle Apple SDK into Swift or Objective-C.\n#### Swift Example\n\n```swift\nimport mParticle_Apple_SDK\n\nfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -\u003e Bool {\n        \n       // Override point for customization after application launch.\n        let mParticleOptions = MParticleOptions(key: \"\u003c\u003c\u003cApp Key Here\u003e\u003e\u003e\", secret: \"\u003c\u003c\u003cApp Secret Here\u003e\u003e\u003e\")\n        \n       //Please see the Identity page for more information on building this object\n        let request = MPIdentityApiRequest()\n        request.email = \"email@example.com\"\n        mParticleOptions.identifyRequest = request\n        mParticleOptions.onIdentifyComplete = { (apiResult, error) in\n            NSLog(\"Identify complete. userId = %@ error = %@\", apiResult?.user.userId.stringValue ?? \"Null User ID\", error?.localizedDescription ?? \"No Error Available\")\n        }\n        mParticleOptions.onAttributionComplete = { (attributionResult, error) in\n            NSLog(\"Attribution Complete. attributionResults = %@\", attributionResult?.linkInfo ?? \"Null attributionResults\")\n        }\n        \n       //Start the SDK\n        MParticle.sharedInstance().start(with: mParticleOptions)\n        \n       return true\n}\n```\n\n#### Objective-C Example\n\nFor apps supporting iOS 8 and above, Apple recommends using the import syntax for **modules** or **semantic import**. However, if you prefer the traditional CocoaPods and static libraries delivery mechanism, that is fully supported as well.\n\nIf you are using mParticle as a framework, your import statement will be as follows:\n\n```objective-c\n@import mParticle_Apple_SDK;                // Apple recommended syntax, but requires \"Enable Modules (C and Objective-C)\" in pbxproj\n#import \u003cmParticle_Apple_SDK/mParticle.h\u003e   // Works when modules are not enabled\n\n```\n\nOtherwise, for CocoaPods without `use_frameworks!`, you can use either of these statements:\n\n```objective-c\n#import \u003cmParticle-Apple-SDK/mParticle.h\u003e\n#import \"mParticle.h\"\n```\n\nNext, you'll need to start the SDK:\n\n```objective-c\n- (BOOL)application:(UIApplication *)application\n        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {\n\n    MParticleOptions *mParticleOptions = [MParticleOptions optionsWithKey:@\"REPLACE ME\"\n                                                                   secret:@\"REPLACE ME\"];\n    \n    //Please see the Identity page for more information on building this object\n    MPIdentityApiRequest *request = [MPIdentityApiRequest requestWithEmptyUser];\n    request.email = @\"email@example.com\";\n    mParticleOptions.identifyRequest = request;\n    mParticleOptions.onIdentifyComplete = ^(MPIdentityApiResult * _Nullable apiResult, NSError * _Nullable error) {\n        NSLog(@\"Identify complete. userId = %@ error = %@\", apiResult.user.userId, error);\n    };\n    mParticleOptions.onAttributionComplete(MPAttributionResult * _Nullable attributionResult, NSError * _Nullable error) {\n        NSLog(@\"Attribution Complete. attributionResults = %@\", attributionResult.linkInfo)\n    }\n    \n    [[MParticle sharedInstance] startWithOptions:mParticleOptions];\n    \n    return YES;\n}\n```\n\nSee [Identity](https://docs.mparticle.com/developers/sdk/ios/idsync/) for more information on supplying an `MPIdentityApiRequest` object during SDK initialization.\n\n\n### \u003ca name=\"Web\"\u003e\u003c/a\u003eWeb\n\n\nAdd the mParticle snippet to your `web/index.html` file as high as possible on the page within the \u003chead\u003e tag, per our [Web Docs](https://docs.mparticle.com/developers/sdk/web/getting-started/).\n```html\n\u003cscript type=\"text/javascript\"\u003e\n  //configure the SDK\n  window.mParticle = {\n      config: {\n          isDevelopmentMode: true,\n          identifyRequest: {\n              userIdentities: {\n                  email: 'email@example.com',\n                  customerid: '123456',\n              },\n          },\n          identityCallback: (response) {\n              console.log(response);\n          },\n          dataPlan: {\n            planId: 'my_plan_id',\n            planVersion: 2\n          }\n      },\n  };\n\n  //load the SDK\n  (\n  function(t){window.mParticle=window.mParticle||{};window.mParticle.EventType={Unknown:0,Navigation:1,Location:2,Search:3,Transaction:4,UserContent:5,UserPreference:6,Social:7,Other:8};window.mParticle.eCommerce={Cart:{}};window.mParticle.Identity={};window.mParticle.config=window.mParticle.config||{};window.mParticle.config.rq=[];window.mParticle.config.snippetVersion=2.3;window.mParticle.ready=function(t){window.mParticle.config.rq.push(t)};var e=[\"endSession\",\"logError\",\"logBaseEvent\",\"logEvent\",\"logForm\",\"logLink\",\"logPageView\",\"setSessionAttribute\",\"setAppName\",\"setAppVersion\",\"setOptOut\",\"setPosition\",\"startNewSession\",\"startTrackingLocation\",\"stopTrackingLocation\"];var o=[\"setCurrencyCode\",\"logCheckout\"];var i=[\"identify\",\"login\",\"logout\",\"modify\"];e.forEach(function(t){window.mParticle[t]=n(t)});o.forEach(function(t){window.mParticle.eCommerce[t]=n(t,\"eCommerce\")});i.forEach(function(t){window.mParticle.Identity[t]=n(t,\"Identity\")});function n(e,o){return function(){if(o){e=o+\".\"+e}var t=Array.prototype.slice.call(arguments);t.unshift(e);window.mParticle.config.rq.push(t)}}var dpId,dpV,config=window.mParticle.config,env=config.isDevelopmentMode?1:0,dbUrl=\"?env=\"+env,dataPlan=window.mParticle.config.dataPlan;dataPlan\u0026\u0026(dpId=dataPlan.planId,dpV=dataPlan.planVersion,dpId\u0026\u0026(dpV\u0026\u0026(dpV\u003c1||dpV\u003e1e3)\u0026\u0026(dpV=null),dbUrl+=\"\u0026plan_id=\"+dpId+(dpV?\"\u0026plan_version=\"+dpV:\"\")));var mp=document.createElement(\"script\");mp.type=\"text/javascript\";mp.async=true;mp.src=(\"https:\"==document.location.protocol?\"https://jssdkcdns\":\"http://jssdkcdn\")+\".mparticle.com/js/v2/\"+t+\"/mparticle.js\" + dbUrl;var c=document.getElementsByTagName(\"script\")[0];c.parentNode.insertBefore(mp,c)}\n  )(\"REPLACE WITH API KEY\");\n\u003c/script\u003e\n```\nFor more help, see the [full Web set up docs](https://docs.mparticle.com/developers/sdk/web/getting-started/#create-an-input).\n\n## Usage\n\nEach of our Dart methods is mapped to an underlying mParticle SDK at the platform level. Note that per Dart's [documentation](https://flutter.dev/docs/development/platform-integration/platform-channels#architecture, calling into platform specific code is asynchronous to ensure the user interface remains responsive.  In your code, you can swap usage between `async` and `then` in accordance to your app's requirements.\n\nFor a full description of all classes, methods, and properties, see the [mParticle Flutter SDK API Reference](https://pub.dev/documentation/mparticle_flutter_sdk/latest/).\n\n### Import\n\n**Importing** the module:\n```dart\nimport 'package:mparticle_flutter_sdk/mparticle_flutter_sdk.dart';\n```\n\nYou must first call `getInstance` on `MparticleFlutterSdk` before each method is called.  This ensures the underlying mParticle SDK has been initialized.  Per Flutter's [plugin documentation](https://flutter.dev/docs/development/platform-integration/platform-channels),  messages between the Dart plugin and underlying platforms must be passed asynchronously to ensure the user interface remains responsive. Therefore, to ensure code is performant to your team's requirements, you may refactor instances of `await` with `then` and vice versa in the examples below.\n\n```dart\nMparticleFlutterSdk? mpInstance = await MparticleFlutterSdk.getInstance();\n```\n\n### Custom Events\n\nTo log events, import mParticle `EventTypes` and `MPEvent` to write proper event logging calls:\n\n```dart\nimport 'package:mparticle_flutter_sdk/events/event_type.dart';\nimport 'package:mparticle_flutter_sdk/events/mp_event.dart';\n\nMPEvent event = MPEvent(\n    eventName: 'Test event logged',\n    eventType: EventType.Navigation)\n  ..customAttributes = { 'key1': 'value1' }\n  ..customFlags = { 'flag1': 'value1' };\nmpInstance?.logEvent(event);\n```\n\nIf you have a high-volume event that you would like to forward to client side kits but exclude from uploading to mParticle, set a boolean flag per event.\n\n```dart\nimport 'package:mparticle_flutter_sdk/events/event_type.dart';\nimport 'package:mparticle_flutter_sdk/events/mp_event.dart';\n\nMPEvent event = MPEvent(\n    eventName: 'Test event logged',\n    eventType: EventType.Navigation)\n    ..customAttributes = {'key1': 'value1'}\n    ..customFlags = {'flag1': 'flagValue1'}\n    ..shouldUploadEvent = false;\nmpInstance?.logEvent(event);\n```\n\nBy default, all events upload to the mParticle server unless explicitly set not to.  This is also available on Commerce Events when calling `logCommerceEvent`.  Support for `logScreenEvent` will be coming in the future.\n\nTo log screen events, import mParticle `ScreenEvent`:\n\n```dart\nimport 'package:mparticle_flutter_sdk/events/screen_event.dart';\n\nScreenEvent screenEvent =\n    ScreenEvent(eventName: 'Screen event logged')\n    ..customAttributes = {'key1': 'value1'}\n    ..customFlags = {'flag1': 'flagValue1'};\nmpInstance?.logScreenEvent(screenEvent);\n```\n\n### Commerce Events\n\nTo log product commerce events, import `CommerceEvent`, `Product` and `ProductActionType` (optionally `TransactionAttributes`)\n\n```dart\nimport 'package:mparticle_flutter_sdk/events/commerce_event.dart';\nimport 'package:mparticle_flutter_sdk/events/product.dart';\nimport 'package:mparticle_flutter_sdk/events/product_action_type.dart';\nimport 'package:mparticle_flutter_sdk/events/transaction_attributes.dart';\n\nfinal Product product1 = Product(name: 'Orange', sku: '123abc', price: 2.4);\nfinal Product product2 = Product(\n    name: 'Apple',\n    sku: '456abc',\n    price: 4.1,\n    quantity: 2,\n    variant: 'variant',\n    category: 'category',\n    brand: 'brand',\n    position: 1,\n    couponCode: 'couponCode',\n    attributes: {'key1': 'value1'});\nfinal TransactionAttributes transactionAttributes =\n    TransactionAttributes(\n        transactionId: '123456',\n        affiliation: 'affiliation',\n        couponCode: '12412342',\n        shipping: 1.34,\n        tax: 43.23,\n        revenue: 242.23);\nCommerceEvent commerceEvent = CommerceEvent.withProduct(\n    productActionType: ProductActionType.Purchase,\n    product: product1)\n..products.add(product2)\n..transactionAttributes = transactionAttributes\n..currency = 'US'\n..screenName = 'One Click Purchase'\n..customAttributes = {\"foo\": \"bar\", \"fuzz\": \"baz\"}\n..customFlags = {\n    \"flag1\": \"val1\",\n    \"flag2\": [\"val2\", \"val3\"]\n};\nmpInstance?.logCommerceEvent(commerceEvent);\n```\n\nTo log promotion commerce events, import `CommerceEvent`, `Promotion` and `PromotionActionType`:\n\n```dart\nimport 'package:mparticle_flutter_sdk/events/commerce_event.dart';\nimport 'package:mparticle_flutter_sdk/events/promotion.dart';\nimport 'package:mparticle_flutter_sdk/events/promotion_action_type.dart';\n\nfinal Promotion promotion1 = Promotion(\n    promotionId: '12312',\n    creative: 'Jennifer Slater',\n    name: 'BOGO Bonanza',\n    position: 'top');\nfinal Promotion promotion2 = Promotion(\n    promotionId: '15632',\n    creative: 'Gregor Roman',\n    name: 'Eco Living',\n    position: 'mid');\n\nCommerceEvent commerceEvent = CommerceEvent.withPromotion(\n    promotionActionType: PromotionActionType.View,\n    promotion: promotion1)\n..promotions.add(promotion2)\n..currency = 'US'\n..screenName = 'PromotionScreen'\n..customAttributes = {\"foo\": \"bar\", \"fuzz\": \"baz\"}\n..customFlags = {\n    \"flag1\": \"val1\",\n    \"flag2\": [\"val2\", \"val3\"]\n};\nmpInstance?.logCommerceEvent(commerceEvent);\n```\n\nTo log impression commerce events, import `CommerceEvent`, `Impression` and `Product`\n\n```dart\nimport 'package:mparticle_flutter_sdk/events/commerce_event.dart';\nimport 'package:mparticle_flutter_sdk/events/impression.dart';\nimport 'package:mparticle_flutter_sdk/events/product.dart';\n\nfinal Product product1 = Product(\n    name: 'Orange', sku: '123abc', price: 2.4, quantity: 1);\nfinal Product product2 = Product(\n    name: 'Apple',\n    sku: '456abc',\n    price: 4.1,\n    quantity: 2,\n    variant: 'variant',\n    category: 'category',\n    brand: 'brand',\n    position: 1,\n    couponCode: 'couponCode',\n    attributes: {'key1': 'value1'});\nfinal Impression impression1 = Impression(\n    impressionListName: 'produce',\n    products: [product1, product2]);\nfinal Impression impression2 = Impression(\n    impressionListName: 'citrus', products: [product1]);\nCommerceEvent commerceEvent =\n    CommerceEvent.withImpression(impression: impression1)\n    ..impressions.add(impression2)\n    ..currency = 'US'\n    ..screenName = 'ImpressionScreen'\n    ..customAttributes = {\"foo\": \"bar\", \"fuzz\": \"baz\"}\n    ..customFlags = {\n        \"flag1\": \"val1\",\n        \"flag2\": [\"val2\", \"val3\"]\n    };\nmpInstance?.logCommerceEvent(commerceEvent);\n```\n\n### User\nGet the current user in order to apply and remove attributes, tags, etc.\n\n```dart\nvar user = await mpInstance?.getCurrentUser();\n```\n\nUser Attributes:\n\n```dart\nuser?.setUserAttribute(key: 'points', value: '1');\n```\n\n```dart\nuser?.setUserAttributeArray(\n    key: 'arrayOfStrings', value: ['a', 'b', 'c']);\n```\n\n```dart\nuser?.setUserTag(tag: 'tag1');\n```\n\n```dart\nuser?.getUserAttributes();\n```\n\n\n```dart\nuser?.removeUserAttribute(key: 'points');\n```\n\n```dart\nuser?.getUserIdentities().then((identities) {\n    print(identities); // Map\u003cIdentityType, String\u003e\n});\n```\n\n\n### IDSync\nIDSync is mParticle’s identity framework, enabling our customers to create a unified view of the customer. To read more about IDSync, see [here](https://docs.mparticle.com/guides/idsync/introduction).\n\nAll IDSync calls require an `Identity Request`.\n\n#### IdentityRequest\n\n```dart\nimport 'package:mparticle_flutter_sdk/identity/identity_type.dart';\n\nvar identityRequest = MparticleFlutterSdk.identityRequest;\nidentityRequest\n    .setIdentity(\n        identityType: IdentityType.CustomerId,\n        value: 'customerid')\n    .setIdentity(\n        identityType: IdentityType.Email,\n        value: 'email@gmail.com');\n```\n\nAfter an IdentityRequest is passed to one of the following IDSync methods -  `identify`, `login`, `logout`, or `modify`.\n\nImport the `SuccessResponse` and `FailureResponse` classes to write proper callbacks for Identity methods.  For brevity, we included an example of full error handling in only the `identify` example below, but this error handling can be used for any of the Identity calls.\n\n#### Identify\n\nThe following is a full Identify example with error and success handling.  You can adapt the following example with `login`, `modify`, and `logout`.\n\n```dart\nimport 'package:mparticle_flutter_sdk/identity/identity_api_result.dart';\nimport 'package:mparticle_flutter_sdk/identity/identity_api_error_response.dart';\n\nvar identityRequest = MparticleFlutterSdk.identityRequest;\n\nmpInstance?.identity\n    .identify(identityRequest: identityRequest)\n    .then(\n        (IdentityApiResult successResponse) =\u003e\n            print(\"Success Response: $successResponse\"),\n        onError: (error) {\n            var failureResponse = error as IdentityAPIErrorResponse;\n            print(\"Failure Response: $failureResponse\");\n\n            // It is possible for either a client error or a server error to occur during identity calls.\n            // First check for the client side error, then you can check the http code for the server error.\n            // More details can be found in the platform specific IDSync error handling:\n                // iOS - https://docs.mparticle.com/developers/sdk/ios/idsync/#error-handling\n                // Web - https://docs.mparticle.com/developers/sdk/web/idsync/#error-handling\n                // Android - https://docs.mparticle.com/developers/sdk/android/idsync/#idsync-status-codes\n            if (failureResponse.clientErrorCode != null) {\n                switch (failureResponse.clientErrorCode) {\n                case IdentityClientErrorCodes.RequestInProgress:\n                    // there is an Identity request in progress, wait for it to complete before attempting another\n                case IdentityClientErrorCodes.ClientSideTimeout:\n                case IdentityClientErrorCodes.ClientNoConnection:\n                    // retry the IDSync request\n                case IdentityClientErrorCodes.SSLError:\n                    // SSL configuration issue. \n                case IdentityClientErrorCodes.OptOut:\n                    // The user has opted out of data collection\n                case IdentityClientErrorCodes.Unknown:\n                    // \n                case IdentityClientErrorCodes.ActiveSession:\n                case IdentityClientErrorCodes.ValidationIssue:\n                    // A web error that should never arise due to Dart's stronger typing\n                case IdentityClientErrorCodes.NativeIdentityRequest:\n                default:\n                    print(failureResponse.clientErrorCode);\n                }\n            }\n            int? httpCode = failureResponse.httpCode;\n            if (httpCode != null \u0026\u0026 httpCode \u003e= 400) {\n                switch (httpCode) {\n                case 400:\n                case 401:\n                case 429:\n                case 529:\n                default:\n                    failureResponse.errors.forEach(\n                        (error) =\u003e print('${error.code}\\n${error.message}'));\n                }\n            }\n        }\n    );\n```\n\n#### Login\n\nPartial example - you can adapt the identify example above with login, modify, and logout.\n\n```dart\nvar identityRequest = MparticleFlutterSdk.identityRequest;\nidentityRequest\n    .setIdentity(\n        identityType: IdentityType.CustomerId,\n        value: 'customerid2')\n    .setIdentity(\n        identityType: IdentityType.Email,\n        value: 'email2@gmail.com');\n\nmpInstance?.identity.login(identityRequest: identityRequest).then(\n    (IdentityApiResult successResponse) =\u003e\n        print(\"Success Response: $successResponse\"),\n    onError: (error) {\n        var failureResponse = error as IdentityAPIErrorResponse;\n        print(\"Failure Response: $failureResponse\");\n    });\n    \n```\n\n#### Modify\n\nPartial example - you can adapt the `identify` example above with `login`, `modify`, and `logout`.\n\n```dart\nvar identityRequest = MparticleFlutterSdk.identityRequest;\nidentityRequest\n    .setIdentity(\n        identityType: IdentityType.CustomerId,\n        value: 'customerid3')\n    .setIdentity(\n        identityType: IdentityType.Email,\n        value: 'email3@gmail.com');\n\nmpInstance?.identity\n    .modify(identityRequest: identityRequest)\n    .then(\n        (IdentityApiResult successResponse) =\u003e\n            print(\"Success Response: $successResponse\"),\n        onError: (error) {\n            var failureResponse = error as IdentityAPIErrorResponse;\n            print(\"Failure Response: $failureResponse\");\n        }\n    );\n```\n\n#### Logout\n\nPartial example - you can adapt the `identify` example above with `login`, `modify`, and `logout`.\n\n```dart \nvar identityRequest = MparticleFlutterSdk.identityRequest;\n// depending on your identity strategy, you may have identities added to your identityRequestk\n\nmpInstance?.identity\n    .logout(identityRequest: identityRequest)\n    .then(\n        (IdentityApiResult successResponse) =\u003e\n            print(\"Success Response: $successResponse\"),\n        onError: (error) {\n            var failureResponse = error as IdentityAPIErrorResponse;\n            print(\"Failure Response: $failureResponse\");\n        }\n    );\n```\n\n#### Aliasing Users\nThis is a feature to transition data from \"anonymous\" users to \"known\" users.  To learn more about user aliasing, see [here](https://docs.mparticle.com/guides/idsync/aliasing/).\n```dart\nmpInstance?.identity\n    .login(identityRequest: identityRequest)\n    .then((IdentityApiResult successResponse) {\n    String? previousMPID =\n        successResponse.previousUser?.getMPID();\n    if (previousMPID != null) {\n        var userAliasRequest = AliasRequest(\n            sourceMpid: previousMPID,\n            destinationMpid: successResponse.user.getMPID());\n        mpInstance?.identity\n            .aliasUsers(aliasRequest: userAliasRequest);\n        }\n    }\n);\n```\n\n### Consent\nTo learn more about Consent on mParticle, see [here](https://docs.mparticle.com/guides/consent-management/);\n\n#### GDPR\n\nGDPR Consent requires a user to add it do:\n```dart\nvar user = await mpInstance?.getCurrentUser();\n```\n\nTo set a GDPR Consent State:\n\n```dart\nConsent gdprConsent = Consent(\n    consented: false,\n    document: 'document test',\n    hardwareId: 'hardwareID',\n    location: 'loction test',\n    timestamp: DateTime.now().millisecondsSinceEpoch);\n\nuser?.addGDPRConsentState(consent: gdprConsent, purpose: 'test');\n```\n\nTo get a GDPR Consent State:\n\n```dart\nMap\u003cString, Consent\u003e? gdprConsent = await user?.getGDPRConsentState(); // String is the purpose set above\n```\n\n#### CCPA\n\nTo set a CCPA Consent State:\n\n```dart\nConsent ccpaConsent = Consent(\n    consented: false,\n    document: 'document test',\n    hardwareId: 'hardwareID',\n    location: 'loction test',\n    timestamp: DateTime.now().millisecondsSinceEpoch);\nuser?.addCCPAConsentState(consent: ccpaConsent);\n```\n\nTo get a CCPA Consent State:\n\n```dart\nConsent? ccpaConsent = await user?.getCCPAConsentState();\n```\n\n### Native-only Methods\nA few methods are currently supported only on iOS/Android SDKs:\n\n* Get the SDK's opt out status\n\n    ```dart\n    var isOptedOut = await mpInstance?.getOptOut;\n    mpInstance?.setOptOut(optOutBoolean: !isOptedOut!);\n    ```\n\n* Check if a kit is active\n\n    ```dart\n    import 'package:mparticle_flutter_sdk/kits/kits.dart';\n\n    mpInstance?.isKitActive(kit: Kits['Braze']!).then((isActive) {\n        print(isActive);\n    });\n    ```\n\n* Push Registration\n\n    The method `mpInstance.logPushRegistration()` accepts two parameters. For Android, provide both `pushToken` and `senderId`. For iOS, provide the push token in the first parameter, and simply pass `null` for the second parameter\n\n    #### Android\n\n    ```dart\n    mpInstance?.logPushRegistration(pushToken: 'pushToken123', senderId: 'senderId123');\n    ```\n\n    #### iOS\n\n    ```dart\n    mpInstance?.logPushRegistration(pushToken: 'pushToken123', senderId: null);\n    ```\n\n* Set App Tracking Transparency (ATT) Status\n\n    For iOS, you can set a user's ATT status as follows:\n    import 'package:mparticle_flutter_sdk/apple/authorization_status.dart';\n\n    ```dart\n    \n    mpInstance?.setATTStatus(\n          attStatus: MPATTAuthorizationStatus.Authorized,\n          timestampInMillis: DateTime.now().millisecondsSinceEpoch);\n    ```\n\n\n# License\n\nApache 2.0\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmparticle%2Fmparticle-flutter-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmparticle%2Fmparticle-flutter-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmparticle%2Fmparticle-flutter-sdk/lists"}