flutterfire Documentation

A collection of Firebase plugins for Flutter apps.

9,195 stars Dart Dart 1 file Β· ~14,555 tokens #dart#firebase#flutter#google
RAW Doc

File: README.md


[Changelog] β€’ [Packages]


FlutterFire is a set of Flutter plugins
that enable Flutter apps to use Firebase services. You can follow an example that shows
how to use these plugins in
the Firebase for Flutter codelab.

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile,
web, and desktop from a single codebase. Flutter is used by developers and organizations around the world, and is free
and open source.


Documentation


Stable Plugins

Name pub.dev Firebase Product Documentation View Source Android iOS Web MacOS Windows
Analytics πŸ”— πŸ“– firebase_analytics βœ” βœ” βœ” Ξ² N/A
App Check πŸ”— πŸ“– firebase_app_check βœ” βœ” βœ” Ξ² N/A
Authentication πŸ”— πŸ“– firebase_auth βœ” βœ” βœ” Ξ² (*)
Cloud Firestore πŸ”— πŸ“– cloud_firestore βœ” βœ” βœ” Ξ² (*)
Cloud Functions πŸ”— πŸ“– cloud_functions βœ” βœ” βœ” Ξ² N/A
Cloud Messaging πŸ”— πŸ“– firebase_messaging βœ” βœ” βœ” Ξ² N/A
Cloud Storage πŸ”— πŸ“– firebase_storage βœ” βœ” βœ” Ξ² (*)
Core πŸ”— πŸ“– firebase_core βœ” βœ” βœ” Ξ² (*)
Crashlytics πŸ”— πŸ“– firebase_crashlytics βœ” βœ” N/A Ξ² N/A
Data Connect πŸ”— πŸ“– firebase_data_connect βœ” βœ” βœ” N/A N/A
In-App Messaging πŸ”— πŸ“– firebase_in_app_messaging βœ” βœ” N/A N/A N/A
Installations πŸ”— πŸ“– firebase_app_installations βœ” βœ” βœ” Ξ² N/A
Performance Monitoring πŸ”— πŸ“– firebase_performance βœ” βœ” βœ” N/A N/A
Realtime Database πŸ”— πŸ“– firebase_database βœ” βœ” βœ” Ξ² N/A
Remote Config πŸ”— πŸ“– firebase_remote_config βœ” βœ” βœ” Ξ² N/A

(*) for development only. Production on Windows is not supported.

Preview Plugins

Name pub.dev Firebase Product Documentation View Source Android iOS Web MacOS
ML Model Downloader (deprecated) πŸ”— πŸ“– firebase_ml_model_downloader βœ” βœ” N/A Ξ²

Issues

Please file FlutterFire specific issues, bugs, or feature requests in
our issue tracker.

Plugin issues that are not specific to FlutterFire can be filed in
the Flutter issue tracker.

Contributing

If you wish to contribute a change to any of the existing plugins in this repo, please review
our contribution guide
and open a pull request.


File: docs/perf-mon/_custom-code-traces.md

{# This content gets published to the following location: #}
{# https://firebase.google.com/docs/perf-mon/custom-code-traces?platform=flutter #}

Performance Monitoring collects traces to help you monitor the performance of your app. A
trace is a report of performance data captured between two points in time in
your app.

You can create your own traces to monitor performance data associated with
specific code in your app. With a custom code trace, you can measure how
long it takes your app to complete a specific task or a set of tasks, for
example loading a set of images or querying your database.

The default metric for a custom code trace is its "duration" (the time between
the starting and stopping points of the trace), but you can add
custom metrics, as well.

In your code, you define the beginning and the end of a custom code trace using
the APIs provided by the Performance Monitoring SDK.

Custom code traces can be started anytime after they've been created, and they
are thread safe.

Since the default metric collected for these traces is "duration", they are
sometimes called "Duration traces".

You can view data from these traces in the Custom traces subtab of the traces
table, which is at the bottom of the Performance dashboard (learn more about
using the console later on this page).

Note: Starting and stopping traces too rapidly can be resource intensive, so
you should avoid creating custom code traces at high frequencies (for example,
once per frame in games).

Default attributes, custom attributes, and custom metrics {:#attributes-and-metrics}

For custom code traces, Performance Monitoring automatically logs
default attributes
(common metadata like app version, country, device, etc.)
so that you can filter the data for the trace in the Firebase console. You
can also add and monitor custom attributes
(such as, game level or user properties).

You can further configure a custom code trace to record
custom metrics for performance-related events that
occur within the trace's scope. For example, you can create a custom metric for
the number of cache hits and misses or the number of times that the UI becomes
unresponsive for a noticeable period of time.

Custom attributes and custom metrics display in the Firebase console
alongside the default attributes and default metric for the trace.

Add custom code traces {:#add-custom-code-traces}

Use the Performance Monitoring Trace API
to add custom code traces to monitor specific application code.

Note the following:

  • An app can have multiple custom code traces.
  • More than one custom code trace can run at the same time.
  • Names for custom code traces must meet the following requirements:
    no leading or trailing whitespace, no leading underscore (_) character,
    and max length is 100 characters.
  • Custom code traces support adding custom metrics and
    custom attributes.

To start and stop a custom code trace, wrap the code that you want to trace with
code similar to the following:

dart
Trace customTrace = FirebasePerformance.instance.newTrace('custom-trace');
await customTrace.start();

// Code you want to trace

await customTrace.stop();

Add custom metrics to custom code traces {:#add-custom-metrics}

Use the Performance Monitoring Trace API
to add custom metrics to custom code traces.

Note the following:

  • Names for custom metrics must meet the following requirements:
    no leading or trailing whitespace, no leading underscore (_) character,
    and max length is 100 characters.
  • Each custom code trace can record up to 32 metrics (including the default
    Duration metric).

To add a custom metric, add a line of code similar to the following each time
that the event occurs. For example, this custom metric counts
performance- related events that occur in your app, such as cache hits or
retries.

dart
Trace customTrace = FirebasePerformance.instance.newTrace("custom-trace");
await customTrace.start();

// Code you want to trace

customTrace.incrementMetric("metric-name", 1);

// More code

await customTrace.stop();

Create custom attributes for custom code traces {:#create-custom-attributes}

To use custom attributes, add code to your app that defines the attribute and
associates it with a specific custom code trace. You can set the custom
attribute anytime between when the trace starts and when the trace stops.

Note the following:

  • Names for custom attributes must meet the following requirements:
    no leading or trailing whitespace, no leading underscore (_) character,
    and max length is 32 characters.

  • Each custom code trace can record up to 5 custom attributes.

  • You shouldn't use custom attributes that contain information that personally
    identifies an individual to Google.

    {{'

    '}}

dart
Trace trace = FirebasePerformance.instance.newTrace("test_trace");

// Update scenario.
trace.putAttribute("experiment", "A");

// Reading scenario.
String? experimentValue = trace.getAttribute("experiment");

// Delete scenario.
trace.removeAttribute("experiment");

// Read attributes.
Map<String, String> traceAttributes = trace.getAttributes();

Track, view, and filter performance data {:#monitor-in-console}

Track specific metrics in your dashboard {:#track-in-dashboard}

To learn how your key metrics are trending, add them to your metrics board at
the top of the Performance dashboard. You can quickly identify regressions by
seeing week-over-week changes or verify that recent changes in your code are
improving performance.

To add a metric to your metrics board, go to the Performance dashboard
in the Firebase console, then click the Dashboard tab. Click an empty metric
card, then select an existing metric to add to your board. Click the vertical
ellipsis (⋮) on a populated metric card for more options, like to
replace or remove a metric.

The metrics board shows collected metric data over time, both in graphical form
and as a numerical percentage change.

Learn more about using the dashboard.

View traces and their data {:#view-traces-and-data}

To view your traces, go to the Performance dashboard
in the Firebase console, scroll down to the traces table, then click the
appropriate subtab. The table displays some top metrics for each trace, and you
can even sort the list by the percentage change for a specific metric.

If you click a trace name in the traces table, you can then click through
various screens to explore the trace and drill down into metrics of interest.
On most pages, you can use the Filter button (top-left of the screen) to
filter the data by attribute, for example:

  • Filter by App version to view data about a past release or your latest
    release
  • Filter by Device to learn how older devices handle your app
  • Filter by Country to make sure your database location isn't affecting a
    specific region

Learn more about viewing data for your traces.

Next Steps

  • Learn more about
    using attributes to examine performance data.

  • Learn more about how to
    track performance issues in the
    Firebase console.

  • Set up alerts for code changes that are degrading
    the performance of your app. For example, you can configure an email alert for
    your team if the duration of a specific custom code trace exceeds a
    threshold that you set.


File: docs/perf-mon/_custom-network-traces.md

{# This content gets published to the following location: #}
{# https://firebase.google.com/docs/perf-mon/custom-network-traces?platform=flutter #}

Performance Monitoring collects traces to help you monitor the performance of your app. A
trace is a report of performance data captured between two points in time in
your app.

The
network request traces automatically collected by Performance Monitoring
include most network requests for your app. However, some requests might not be
reported or you might use a different library to make network requests. In these
cases, you can use the Performance Monitoring API to manually instrument
custom network request traces. Custom network request traces are only
supported for Apple and Android apps.

The default metrics for a custom network request trace are the same as those for
the network request traces automatically collected by Performance Monitoring, specifically
response time, response and request payload size, and success rate. Custom
network request traces do not support adding custom metrics.

In your code, you define the beginning and the end of a custom network request
trace using the APIs provided by the Performance Monitoring SDK.

Custom network request traces appear in the Firebase console alongside the
network requests that Performance Monitoring captures automatically
(in the Network requests subtab of the traces table).

Add custom network request traces {:#add-custom-network-traces}

Use the Performance Monitoring HttpMetric API
to add custom network request traces to monitor specific network requests.

To manually instrument custom network requests in Performance Monitoring, add code similar
to the following:

dart
final metric = FirebasePerformance.instance
    .newHttpMetric("https://www.google.com", HttpMethod.Get);

await metric.start();
final response = await http.get(Uri.parse("https://www.google.com/"));
await metric.stop();

Custom network request traces also support adding custom attributes
but not custom metrics.

Next steps

  • Set up alerts for network requests that are degrading
    the performance of your app. For example, you can configure an email alert for
    your team if the response time for a specific URL pattern exceeds a
    threshold that you set.

File: docs/perf-mon/_disable-sdk.md

{# This content gets published to the following location: #}
{# https://firebase.google.com/docs/perf-mon/disable-sdk?platform=flutter #}

During app development and testing, you might find it useful to disable
Performance Monitoring.

For example, by
disabling Performance Monitoring during your app build process,
you can:

  • Disable certain functionalities of Performance Monitoring in your debug
    builds, but re-enable the functionalities for your release build.

  • Disable Performance Monitoring when building your app, but allow your app to
    re-enable it at runtime.

  • Disable Performance Monitoring when building your app, and do not allow your
    app to re-enable it at runtime.

You can also build your app with Performance Monitoring enabled, but
use Firebase Remote Config to give you
flexibility to disable (and re-enable) Performance Monitoring in your production
app. With this option, you can even configure your app to let users opt-in or
opt-out of using Performance Monitoring.

Disable Performance Monitoring during your app build process {: #disable-during-build}

One situation where disabling Performance Monitoring during your app build
process could be useful is to avoid reporting performance data from a
pre-release version of your app during app development and testing.

To do so, see the platform-specific iOS+ and
Android docs.

Disable your app at runtime using Remote Config {: #disable-with-remote-config}

Firebase Remote Config lets
you make changes to the behavior and appearance of your app, so it provides an
ideal way to let you disable Performance Monitoring in deployed instances of
your app.

For example, suppose you want to use a parameter called perf_disable to
remotely control Performance Monitoring. Add the following to your startup code
to enable or disable Performance Monitoring:

dart
// Activate previously-fetched values, falling back on the defaults if
// nothing is available yet.
await FirebaseRemoteConfig.instance
    .setDefaults(YOUR_REMOTE_CONFIG_DEFAULTS);
await FirebaseRemoteConfig.instance.activate();

// Enable or disable Performance Monitoring based on the value of
// "perf_disable".
final perfMonDisabled =
    FirebaseRemoteConfig.instance.getBool("perf_disable");
FirebasePerformance.instance
    .setPerformanceCollectionEnabled(!perfMonDisabled);

// Fetch values for next time. (Don't await the result!)
FirebaseRemoteConfig.instance.fetch();

Note: This snippet requires an app restart to activate configuration changes.
See Loading strategies for alternatives.


File: docs/perf-mon/get-started.md

Project: /docs/perf-mon/_project.yaml
Book: /docs/_book.yaml
page_type: guide

{% include "_shared/apis/console/_local_variables.html" %}
{% include "_local_variables.html" %}
{% include "docs/perf-mon/_local_variables.html" %}
{% include "_shared/firebase/_snippet_include_comment.html" %}

Get started with Performance Monitoring for Flutter

This quickstart describes how to set up Firebase Performance Monitoring to help
you to gain insight into the performance characteristics of your Flutter apps.

Before you begin

If you haven't already,
configure and initialize Firebase in your Flutter
project.

**Step 1**: Add Performance Monitoring to your app {:#add-perfmon}

  1. From the root directory of your Flutter project, run the following
    command to install the Performance Monitoring Flutter plugin:

    sh {: .devsite-terminal .devsite-click-to-copy data-terminal-prefix="your-flutter-proj$ " }
    flutter pub add firebase_performance
  2. From the root directory of your Flutter project, run the following command:

    sh {: .devsite-terminal .devsite-click-to-copy data-terminal-prefix="your-flutter-proj$ " }
    flutterfire configure

    Running this command ensures that your Flutter app's Firebase configuration
    is up-to-date and, for Android, adds the required Performance Monitoring
    Gradle plugin to your app.

  3. Once complete, rebuild your Flutter project:

    sh {: .devsite-terminal .devsite-click-to-copy data-terminal-prefix="your-flutter-proj$ " }
    flutter run

After you've added the Performance Monitoring SDK, Firebase automatically starts collecting
data related to your app's lifecycle (like
app start time), and
data for HTTP/S network requests.

On Flutter, automatic screen rendering performance monitoring is not possible
for individual Flutter screens. A single view controller encapsulates your
entire Flutter application natively so the underlying native Firebase SDK is
not aware of screen transitions.

Note: When you add Performance Monitoring to your app, the Remote Config SDK is
included as a dependency. If you already use Remote Config, you won't see
any difference. However, if you're new to Remote Config, explore the
Remote Config documentation to learn more
about the various features you'll be able to access in your app.

**Step 2**: Generate performance events for initial data display {:#data-in-console}

Firebase starts processing the events when you successfully add the SDK to your
app. If you're still developing locally, interact with your app to generate
events for initial data collection and processing.

Note: The Performance Monitoring SDK batches events locally then sends them to Firebase
periodically (every 30 seconds) or when the app comes back to foreground. So,
there's a delay between an app interaction and when Firebase receives the event
information from your app.

  1. Continue to develop your app using a simulator or test device.

  2. Generate events by switching your app between background and foreground
    several times, interacting with your app by navigating across screens,
    and/or triggering network requests.

  3. Go to the Performance dashboard
    of the Firebase console. You should see your initial data display within
    a few minutes.

    If you don't see a display of your initial data, review the troubleshooting
    tips
    .

**Step 3**: _(Optional)_ View log messages for performance events {:#view-log-messages}

  1. Check your log messages for any error messages.

    Performance Monitoring tags its log messages with the following tags so that
    you can filter your log messages:

    • iOS+: Firebase/Performance
    • Android: FirebasePerformance
  2. Check for the following types of logs which indicate that Performance Monitoring is
    logging performance events:

    • Logging trace metric: <var>TRACE_NAME</var>, <var>FIREBASE_PERFORMANCE_CONSOLE_URL</var>
    • Logging network request trace: <var>URL</var>
  3. Click on the URL to view your data in the Firebase console. It may take a few
    moments for the data to update in the dashboard.

**Step 4**: _(Optional)_ Add custom monitoring for specific code {:#add-custom-trace}

To monitor performance data associated with specific code in your app, you can
instrument custom code traces.

With a custom code trace, you can measure how long it takes your app to complete
a specific task or set of tasks, such as loading a set of images or querying
your database. The default metric for a custom code trace is its duration, but
you can also add custom metrics, such as cache hits and memory warnings.

In your code, you define the beginning and the end of a custom code trace (and
add any desired custom metrics) using the API provided by the Performance Monitoring SDK.

Visit Add monitoring for specific code
to learn more about these features and how to add them to your app.

**Step 5**: Deploy your app then review results {:#deploy-then-review-results}

After you've validated Performance Monitoring using the an emulator and one or more
test devices, you can deploy the updated version of your app to your users.

You can monitor performance data in the
Performance dashboard
of the Firebase console.

Next steps


File: docs/ml/use-custom-models.md

Project: /docs/_project.yaml
Book: /docs/_book.yaml

Use a custom TensorFlow Lite model with Flutter

If your app uses custom
TensorFlow Lite{:.external} models, you can
use Firebase ML to deploy your models. By deploying models with Firebase, you
can reduce the initial download size of your app and update your app's ML models
without releasing a new version of your app. And, with Remote Config and A/B
Testing, you can dynamically serve different models to different sets of users.

TensorFlow Lite models

TensorFlow Lite models are ML models that are optimized to run on mobile
devices. To get a TensorFlow Lite model:

Note that in the absence of a maintained TensorFlow Lite library for Dart, you
will need to integrate with the native TensorFlow Lite library for your
platforms. This integration is not documented here.

Before you begin

  1. Install and initialize the Firebase SDKs for Flutter
    if you haven't already done so.

  2. From the root directory of your Flutter project, run the following
    command to install the ML model downloader plugin:

    bash
    flutter pub add firebase_ml_model_downloader
  3. Rebuild your project:

    bash
    flutter run

1. Deploy your model {:#deploy}

Deploy your custom TensorFlow models using either the Firebase console or
the Firebase Admin Python and Node.js SDKs. See
Deploy and manage custom models.

After you add a custom model to your Firebase project, you can reference the
model in your apps using the name you specified. At any time, you can deploy a
new TensorFlow Lite model and download the new model onto users' devices by
calling getModel() (see below).

2. Download the model to the device and initialize a TensorFlow Lite interpreter

To use your TensorFlow Lite model in your app, first use the model downloader
to download the latest version of the model to the device. Then, instantiate a
TensorFlow Lite interpreter with the model.

To start the model download, call the model downloader's getModel() method,
specifying the name you assigned the model when you uploaded it, whether you
want to always download the latest model, and the conditions under which you
want to allow downloading.

You can choose from three download behaviors:

Download type Description
localModel Get the local model from the device.
: : If there is no local model available, this
: : behaves like latestModel. Use this
: : download type if you are not interested in
: : checking for model updates. For example,
: : you're using Remote Config to retrieve
: : model names and you always upload models
: : under new names (recommended).
localModelUpdateInBackground Get the local model from the device and
: : start updating the model in the background.
: : If there is no local model available, this
: : behaves like latestModel.
latestModel Get the latest model. If the local model is
: : the latest version, returns the local
: : model. Otherwise, download the latest
: : model. This behavior will block until the
: : latest version is downloaded (not
: : recommended). Use this behavior only in
: : cases where you explicitly need the latest
: : version.

You should disable model-related functionality—for example, grey-out or
hide part of your UI—until you confirm the model has been downloaded.

dart
FirebaseModelDownloader.instance
    .getModel(
        "yourModelName",
        FirebaseModelDownloadType.localModel,
        FirebaseModelDownloadConditions(
          iosAllowsCellularAccess: true,
          iosAllowsBackgroundDownloading: false,
          androidChargingRequired: false,
          androidWifiRequired: false,
          androidDeviceIdleRequired: false,
        )
    )
    .then((customModel) {
      // Download complete. Depending on your app, you could enable the ML
      // feature, or switch from the local model to the remote model, etc.

      // The CustomModel object contains the local path of the model file,
      // which you can use to instantiate a TensorFlow Lite interpreter.
      final localModelPath = customModel.file;

      // ...
    });

Many apps start the download task in their initialization code, but you can do
so at any point before you need to use the model.

3. Perform inference on input data

Now that you have your model file on the device you can use it with the
TensorFlow Lite interpreter to perform inference. In the absence of a maintained
TensorFlow Lite library for Dart, you will need to integrate with the
native TensorFlow Lite libraries{:.external}
for iOS and Android.

Appendix: Model security {:#model_security}

Regardless of how you make your TensorFlow Lite models available to
Firebase ML, Firebase ML stores them in the standard serialized protobuf format in
local storage.

In theory, this means that anybody can copy your model. However,
in practice, most models are so application-specific and obfuscated by
optimizations that the risk is similar to that of competitors disassembling and
reusing your code. Nevertheless, you should be aware of this risk before you use
a custom model in your app.


File: docs/in-app-messaging/_customize-messages.md

{# This content gets published to the following location: #}
{# https://firebase.google.com/docs/in-app-messaging/customize-messaging?platform=flutter #}

Firebase In-App Messaging provides a useful set of preconfigured behaviors and
message types with a default look and feel, but in some cases you may want to
extend behaviors and message content. In-App Messaging allows you to add actions
to messages and customize message look and feel.

Add an action to your message

With actions you can use your in-app messages to direct users to a
website or a specific screen in your app.

Firebase In-App Messaging uses link handlers to process actions. The SDK is
able to use a number of handlers, so if your app already has one, Firebase
In-App Messaging can use that without any further setup. If you don't yet have
a handler, you can use Firebase Dynamic Links.

Add the action to your message using the Firebase console

Once your app has a link handler, you're ready to compose a campaign with
an action. Open the Firebase console to
In-App Messaging,
and start a new campaign or edit an existing campaign. In that campaign, provide
a Card, Button text and Button action, an Image action, or a Banner
action
, where the action is a relevant deep link.

The action's format depends on which message layout you choose. Modals get
action buttons with customizable button text content, text color, and background
color. Images and top banners, on the other hand, become interactive and invoke
the specified action when tapped.


File: docs/in-app-messaging/_get-started.md

{# This content gets published to the following location: #}
{# https://firebase.google.com/docs/in-app-messaging/get-started?platform=flutter #}

Before you begin

Install and initialize the Firebase SDKs for Flutter if you
haven't already done so.

Add the Firebase In-App Messaging SDK to your project

  1. From the root directory of your Flutter project, run the following
    command to install the Firebase In-App Messaging plugin:

    bash
    flutter pub add firebase_in_app_messaging
  2. Rebuild your project:

    bash
    flutter run
  3. Import the Firebase In-App Messaging plugin:

    dart
    import 'package:firebase_in_app_messaging/firebase_in_app_messaging.dart';

Send a test message

Get your app's installation ID

To conserve power, Firebase In-App Messaging only retrieves messages from the
server once per day. That can make testing difficult, so the
Firebase console allows you to specify a test device that displays messages
on demand.

That testing device is determined by a FID.
Find your testing app's FID by checking the console
output when you run your app.

On Android, the message looks like the following:

text
I/FIAM.Headless: Starting InAppMessaging runtime with Installation ID YOUR_INSTALLATION_ID

On iOS, run the app with the runtime command argument -FIRDebugEnabled:

  1. With your Xcode project open, select Product > Scheme > Edit scheme... from
    the top menu bar.
  2. Open the Arguments tab of the dialog that pops up.
  3. Click + Add items under Arguments Passed On Launch.
  4. Enter "-FIRDebugEnabled" in the newly-created field.
  5. Click Close, then run your app.

Once your app starts running, look for the following line in the Xcode console's logs:

text
[Firebase/InAppMessaging][I-IAM180017] Starting InAppMessaging runtime with Firebase Installation ID YOUR_INSTALLATION_ID

Send a message to your testing device

Once you've launched your app on the testing device and you have its
Firebase installation ID (FID), you can try out your Firebase In-App Messaging
setup by sending a test message:

  1. In the {{name_appmanager}}, open Messaging.
  2. If this is your first campaign, click Create your first campaign.
    1. Select Firebase In-App messages and click Create.
  3. Otherwise, on the Campaigns tab, click New campaign.
    1. Select In-App Messaging.
  4. Enter a Title for your first message.
  5. Click Test on your Device
  6. Enter your app's Firebase installation ID in the
    Add an installation ID field.
  7. Click Test to send the message.

Firebase In-App Messaging sends your test message as soon as you click Test. To see the
message, you need to close, then reopen the app on your testing device.

To confirm whether your device is a test device, look for one of the following
log messages.

Android

text
I/FIAM.Headless: Setting this device as a test device

iOS

text
[Firebase/InAppMessaging][I-IAM180017] Seeing test message in fetch response. Turn the current instance into a testing instance.

File: docs/in-app-messaging/_modify-message-behavior.md

{# This content gets published to the following location: #}
{# https://firebase.google.com/docs/in-app-messaging/modify-message-behavior?platform=flutter #}

With little to no coding effort, Firebase In-App Messaging allows you to create,
configure and target rich user interactions, leveraging
the capabilities of Google Analytics out of the box
to tie messaging events to actual user characteristics, activities, and choices.
With some additional Firebase In-App Messaging SDK integration, you can tailor
the behavior of in-app messages even further, responding when users interact
with messages, triggering message events outside the Analytics
framework, and allowing users to control sharing of their personal data related
to messaging interactions.

Respond when users interact with in-app messages

With actions you can use your in-app messages to direct users to a
website or a specific screen in your app.

Your code can respond to basic interactions (clicks and dismissals), to
impressions (verified views of your messages), and to display errors logged and
confirmed by the SDK. For example, when your message is composed as a Card
modal, you might want to track and follow-up on which of two URLs the user
clicked on the Card.

To do so, you will have to use the platform-native APIs.
See the documentation for iOS
and Android.

Trigger in-app messages programmatically

Firebase In-App Messaging by default allows you to trigger in-app messages with
Google Analytics for Firebase events, with no additional integration. You can
also manually trigger events programmatically with the Firebase In-App Messaging SDK's
programmatic triggers.

In the In-App Messaging campaign composer, create a new campaign or select an
existing campaign, and in the Scheduling step of the composer workflow, note the
event ID of a newly-created or existing messaging event. Once noted, instrument
your app to trigger the event by its ID.

dart
FirebaseInAppMessaging.instance.triggerEvent("eventName");

Use campaign custom metadata

In your campaigns, you can specify custom data in a series of key/value pairs.
When users interact with messages, this data is available for you to, for example,
display a promo code.

To do so, you will have to use the platform-native APIs.
See the documentation for iOS
and Android.

Temporarily disable in-app messages

By default, Firebase In-App Messaging renders messages whenever a triggering
condition is satisfied, regardless of an app's current state. If you'd like to
suppress message displays for any reason, for example to avoid interrupting a
sequence of payment processing screens, you can do that with the SDK's
setMessagesSuppressed() method:

dart
FirebaseInAppMessaging.instance.setMessagesSuppressed(true);

Passing true to the method prevents Firebase In-App Messaging from displaying
messages, while false reenables message display. The SDK turns off message
suppression on app restart. Suppressed messages are ignored by the SDK. Their
trigger conditions must be met again while suppression is off before Firebase
In-App Messaging can display them.

Enable opt-out message delivery

By default, Firebase In-App Messaging automatically delivers messages to all app users you target
in messaging campaigns. To deliver those messages, the Firebase In-App Messaging SDK uses
installation IDs to identify each user's app. This means
that In-App Messaging has to send client data, linked to the
installation ID, to Firebase servers. If you'd like to give users
more control over the data they send, disable automatic data collection and give
them a chance to approve data sharing.

To do that, you have to disable automatic initialization for Firebase In-App Messaging, and
initialize the service manually for opt-in users:

  1. Turn off automatic initialization.

    Apple platforms: Add a new key to your Info.plist file:

    • Key: FirebaseInAppMessagingAutomaticDataCollectionEnabled
    • Value: NO

    Android: Add a meta-data tag to your AndroidManifest.xml file:

    xml
    <meta-data
        android:name="firebase_inapp_messaging_auto_data_collection_enabled"
        android:value="false" />
  2. Initialize Firebase In-App Messaging for selected users manually:

    dart
    FirebaseInAppMessaging.instance.setAutomaticDataCollectionEnabled(true);

    Once you set a data collection preference manually, the value persists
    through app restarts, overriding the value in your Info.plist or
    AndroidManifest.xml. If you'd like to disable initialization again, for
    example if a user opts out of collection later, pass false to the
    setAutomaticDataCollectionEnabled() method.


Project: /docs/dynamic-links/_project.yaml
Book: /docs/_book.yaml
page_type: guide

{% include "_local_variables.html" %}
{% include "docs/cpp/_local_variables.html" %}
{% include "docs/dynamic-links/_local_variables.html" %}

{% include "docs/dynamic-links/_deprecation_banner.html" %}

You can create short or long Dynamic Links with the Firebase Dynamic Links Builder API.
This API accepts either a long Dynamic Link or an object containing Dynamic Link
parameters, and returns URLs like the following examples:

text
https://example.com/link/WXYZ
https://example.page.link/WXYZ

Before you can create Dynamic Links in your Android app, you must include the
Firebase SDK. If your app is set up to receive Dynamic Links, you have already
completed these steps and you can skip this section.

  1. Install and initialize the Firebase SDKs for Flutter if you
    haven't already done so.

  2. From the root directory of your Flutter project, run the following
    command to install the Dynamic Links plugin:

    text
    flutter pub add firebase_dynamic_links
  3. If you're building an Android app, open the Project settings
    page of the Firebase console and make sure you've specified your SHA-1
    signing key. If you use App Links, also specify your SHA-256 key.

  4. In the Firebase console, open the Dynamic Links
    section.

    1. If you have not already set up a domain for your Dynamic Links, click the
      Get Started button and follow the prompts.

      If you already have a Dynamic Links domain, take note of it. You need to
      provide a Dynamic Links domain when you programmatically create Dynamic Links.

    2. Recommended: From the "More" (⋮) menu, specify the URL
      patterns allowed in your deep links and fallback links. By doing so,
      you prevent unauthorized parties from creating Dynamic Links that redirect
      from your domain to sites you don't control.

      See Allow specific URL patterns.

To create a Dynamic Link, create a new DynamicLinkParameters object and pass it to
buildLink() or buildShortLink().

The following minimal example creates a long Dynamic Link to
https://www.example.com/ that opens with com.example.app.android on Android
and the app com.example.app.ios on iOS:

dart
final dynamicLinkParams = DynamicLinkParameters(
  link: Uri.parse("https://www.example.com/"),
  uriPrefix: "https://example.page.link",
  androidParameters: const AndroidParameters(packageName: "com.example.app.android"),
  iosParameters: const IOSParameters(bundleId: "com.example.app.ios"),
);
final dynamicLink =
    await FirebaseDynamicLinks.instance.buildLink(dynamicLinkParams);

To create a short Dynamic Link, pass the DynamicLinkParameters object to
buildShortLink(). Building the short link requires a network call.
For example:

dart
final dynamicLinkParams = DynamicLinkParameters(
  link: Uri.parse("https://www.example.com/"),
  uriPrefix: "https://example.page.link",
  androidParameters: const AndroidParameters(packageName: "com.example.app.android"),
  iosParameters: const IOSParameters(bundleId: "com.example.app.ios"),
);
final dynamicLink =
    await FirebaseDynamicLinks.instance.buildShortLink(dynamicLinkParams);

By default, short Dynamic Links are generated with suffixes that are only a few
characters long. Although this makes links more compact, it also introduces
the possibility that someone could guess a valid short link. Often, there's no
harm if someone does so, because the link leads to public information.

However, if your short links lead to user-specific information, you should
create longer links with 17-character suffixes that make it very unlikely that
someone can guess a valid Dynamic Link. To do so, pass ShortDynamicLinkType.unguessable
to the buildShortLink() method:

dart
final unguessableDynamicLink = await FirebaseDynamicLinks.instance.buildShortLink(
    dynamicLinkParams,
    shortLinkType: ShortDynamicLinkType.unguessable,
);

Dynamic Link parameters

You can use the Dynamic Link Builder API to create Dynamic Links with any of the
supported parameters. See the API reference.

The following example creates a Dynamic Link with several common parameters
set:

dart
final dynamicLinkParams = DynamicLinkParameters(
  link: Uri.parse("https://www.example.com/"),
  uriPrefix: "https://example.page.link",
  androidParameters: const AndroidParameters(
    packageName: "com.example.app.android",
    minimumVersion: 30,
  ),
  iosParameters: const IOSParameters(
    bundleId: "com.example.app.ios",
    appStoreId: "123456789",
    minimumVersion: "1.0.1",
  ),
  googleAnalyticsParameters: const GoogleAnalyticsParameters(
    source: "twitter",
    medium: "social",
    campaign: "example-promo",
  ),
  socialMetaTagParameters: SocialMetaTagParameters(
    title: "Example of a Dynamic Link",
    imageUrl: Uri.parse("https://example.com/image.png"),
  ),
);
final dynamicLink =
    await FirebaseDynamicLinks.instance.buildShortLink(dynamicLinkParams);

You can set Dynamic Link parameters with the following methods:

DynamicLink parameters
setLink The link your app will open. Specify a URL that your app can handle,
text
typically the app's content or payload, which initiates app-specific
    logic (such as crediting the user with a coupon or displaying a
    welcome screen). This link must be a well-formatted URL, be properly
    URL-encoded, use either HTTP or HTTPS, and cannot be another Dynamic
    Link.
    When users open a Dynamic Link on a desktop web browser, they
        will load this URL (unless the ofl parameter is specified). If you
        don't have a web equivalent to the linked content, the URL doesn't
        need to point to a valid web resource. In this situation, you
        should set up a redirect from this URL to, for example, your home
        page. |

| setDomainUriPrefix | Your Dynamic Link URL prefix, which you can find in the Firebase console. A
Dynamic Link domain looks like the following examples:

https://example.com/link
https://example.page.link |

AndroidParameters
setFallbackUrl The link to open when the app isn't installed. Specify this to do
text
something other than install your app from the Play Store when the app
    isn't installed, such as open the mobile web version of the content, or
    display a promotional page for your app. |

| setMinimumVersion | The versionCode of the minimum version of your app that can open the
link. If the installed app is an older version, the user is taken to
the Play Store to upgrade the app. |

IosParameters
setAppStoreId Your app's App Store ID, used to send users to the App Store when the
text
app isn't installed |

| setFallbackUrl | The link to open when the app isn't installed. Specify this to do
something other than install your app from the App Store when the app
isn't installed, such as open the mobile web version of the content, or
display a promotional page for your app. |
| setCustomScheme | Your app's custom URL scheme, if defined to be something other than
your app's bundle ID |
| setIpadFallbackUrl | The link to open on iPads when the app isn't installed. Specify this to
do something other than install your app from the App Store when the
app isn't installed, such as open the web version of the content, or
display a promotional page for your app. |
| setIpadBundleId | The bundle ID of the iOS app to use on iPads to open the link. The app
must be connected to your project from the Overview page of the
Firebase console. |
| setMinimumVersion | The version number of the minimum version of your app that can open the
link. This flag is passed to your app when it is opened, and your app
must decide what to do with it. |

NavigationInfoParameters
setForcedRedirectEnabled If set to '1', skip the app preview page when the Dynamic Link is
text
opened, and instead redirect to the app or store. The app preview page
    (enabled by default) can more reliably send users to the most
    appropriate destination when they open Dynamic Links in apps; however,
    if you expect a Dynamic Link to be opened only in apps that can open
    Dynamic Links reliably without this page, you can disable it with this
    parameter. This parameter will affect the behavior of the Dynamic Link
    only on iOS. |
SocialMetaTagParameters
setTitle The title to use when the Dynamic Link is shared in a social post.
setDescription The description to use when the Dynamic Link is shared in a social post.
setImageUrl The URL to an image related to this link. The image should be at least
text
300x200 px, and less than 300 KB. |
GoogleAnalyticsParameters
setSourcesetMediumsetCampaignsetTermsetContent Google Play analytics parameters. These parameters
text
(`utm_source`, `utm_medium`,
 `utm_campaign`, `utm_term`, `utm_content`)
 are passed on to the Play Store as well as appended to the link payload. |
ItunesConnectAnalyticsParameters
setProviderTokensetAffiliateTokensetCampaignToken iTunes Connect analytics parameters. These parameters (pt,
text
`at`, `ct`) are passed to the App Store. |