How to Add In-App Messages to a Flutter App
Tags: flutter, dart, mobiledev
Published: 2022-06-06 19:19:34

---
title: How to Add In-App Messages to a Flutter App
published: true
date: 2022-06-03 20:21:15 UTC
tags: flutter,dart,mobiledev
canonical_url: https://onesignal.com/blog/how-to-add-in-app-messages-to-a-flutter-app/
---

 ![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/how-to-add-in-app-messages-to-a-flutter-app.jpg)

In-app messages (IAM) can help increase user engagement among active users, nudging them towards desired actions with targeted messages and dynamic content. These messages can be automated and personalized based on custom [segmentation and trigger criteria](https://onesignal.com/blog/boost-push-notification-engagement-with-onesignals-segmentation-tool/). This tutorial will cover how to integrate OneSignal IAM into a Flutter app for both Android and iOS. It will also show you how to use message triggers to automate and customize your messages.

## Creating the Flutter Project

Open your terminal and run the following command to create a new Flutter project  
`flutter create flutter_onesignal_iamcd flutter_onesignal_iam`  
Now run the following command to add Onesignal SDK to the flutter project  
`flutter pub add onesignal_flutter`

## Setting up your OneSignal Account

This tutorial requires a OneSignal account. You can either [log in](https://app.onesignal.com/login) to your existing OneSignal account or [create a new account for free](https://app.onesignal.com/signup). Then, click **_+New App/Website_** to begin setting up your OneSignal account.

![How to Add In-App Messages to a Flutter App](https://lh4.googleusercontent.com/37P1h9kX0fQTxgKg50RfFmNRpJV5ym6cAmEqGKNOec36Ni9pMugoMkoD7WjJk8TYWyAeVa5KnMH3rh58uPLhMtuwJJ1J0aAwqYl3tUHMKq56kfiBK1gkxu-joRURQkXkF2B6DEMS)

### Android Setup

As Flutter apps can target both Android and iOS, both of these platforms need to be set up individually. Let’s proceed with setting up Android for now — iOS can be added later.

![How to Add In-App Messages to a Flutter App](https://lh3.googleusercontent.com/1079YxjGproJRdRzcgmoEn1a0wStoczHtPLh2T7cX2jhnbdmI6TJugzAeyspHUVKwW22dq43QdmyoRylInn3uOI-OSy-76F6nf8RCVzBezvyaTrd7mF5_FrO6T1XISPYnHqMkE4m)

Name your app and select _**Google Android (FCM)**_ and use the following guide to [<u>generate a Firebase Server Key</u>](https://documentation.onesignal.com/docs/generate-a-google-server-api-key).

![How to Add In-App Messages to a Flutter App](https://lh6.googleusercontent.com/--c0A23Xt7HOrOzAnrVWuG70tsTimR4Q8wt68y6Al84-S77WWDe3gWGn27PpJUpsxVcC9Ukz5ORIqpxVZPBIcygszg0fkV6XsPiow22R8vw6_9xOHQqfxE9dYjV8jK6DepAarjHW)

After you've input your Firebase Server Key and Firebase Sender ID, click **_Save & Continue_**.

On the next screen, select _ **Flutter** _ as your target SDK.

![How to Add In-App Messages to a Flutter App](https://lh4.googleusercontent.com/49fTc1QegAjP3hoAUqXmbIanKQvNYHRJ7qNQiFm5YRySJttfIhfy4L-wfH1fP0PEix2f5fQAAhvacK10aPFQrs577RhpBXTDsxXAJN7YBcrqQmLMqmwrWEZi1wsLWaVE4rL1o-2x)

On the next page, you'll see your App ID — copy it for future reference. **Don't click _Done_** just yet. The Flutter app needs to be run on your device first before you complete this step.

![How to Add In-App Messages to a Flutter App](https://lh5.googleusercontent.com/521q84nDI0wzckpwbEZKBNcHIesKtfHjnVX1uOYbXxYPivQfgKlluiSKLUGEHccnZj-XKaFLpzw8gyXe_e_AVkR3twnt6eRAZBbDrYekQ3LqkG_AH12-1T4Ud-at_jIb53S96eMd)

The App ID is used to initialize the OneSignal SDK. Add the following code to `main.dart`:

```
import 'package:flutter/material.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    OneSignal.shared.setAppId("YOUR ONESIGNAL APP ID HERE");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('OneSignal IAM'),
      ),
      body: const Center(child: Text('OneSignal IAM Example')),
    );
  }
}

```

Now, run the app on your device. Then, return to your OneSignal account and click on **_Check Subscribed Users_**. A message showing your device model will be shown.

![How to Add In-App Messages to a Flutter App](https://lh5.googleusercontent.com/Bw_Wmiv3Ri2Fnf19tWaV6vI53KsVBYEKlWOaymWDONk0vOUXnjA9k-a_q5REejk16C5Db5_b9LIjjVyW5I00msFfA_pSgGzjgWApeuGwCz3p5nR5yM8DJv3l56V7LJG63ZUHJ_Al)

### iOS Setup

In your OneSignal account, navigate _ **Settings** _ and click on _**Apple iOS (APNs)**_. In this step, you will be asked for an iOS push certificate and its password.

Check out the linked documentation to learn [how to generate an iOS push certificate](https://documentation.onesignal.com/docs/generate-an-ios-push-certificate). The easiest method is to use[OneSignal provisionator](https://onesignal.com/provisionator), which directly generates the p12 file and password without much hassle. Once generated, upload the p12 file and password, and continue to the next screen.

![How to Add In-App Messages to a Flutter App](https://lh4.googleusercontent.com/g-RK42ukOsNazyECQOoa9yLCwENsb3WxMgn33m8_DXCk1wsHgjMdy74OL-S5nAirQinhg46HLWkt7xsxMrWTNnWKpWywHsnSgIqtjwtFnO3RkKxwt9pgTEmgHAWJPDp4AmCojvPlMsOb2fySWQ)

![How to Add In-App Messages to a Flutter App](https://lh5.googleusercontent.com/Uadu5kRL8BxcMZQ9IMMenYy670uHseGf3yGR504sDO_L1saV8wPfKs-5ouH4uDWaFUKcM--LcP-sIiyckbeOxd9Zq8MTzZNbxEpXF9L21BPrtPthcwYi8ZkEVju8IWVASgG-clP6xGhg7UpwyA)

### Upload Your APNs Cert

![How to Add In-App Messages to a Flutter App](https://lh6.googleusercontent.com/VRzrv4qZcGkIrjtez8mRAu40EJexhtWj4T41HFvgkI_XuNzf0HlgVgwgLrR8y7mYqiZWzTB2vbKsGeskkZrtv5zpZViIHPyKFRrOgbIudRlhi1i8QhUw5cSyxGcan53fmIFkiIJq_VEop7cdCw)

The certificate password is the one used to encrypt the exported certificate. If you left the password empty, do not enter a value for **Certificate Password**. OneSignal will verify the certificate can be used for push notifications upon clicking the continue button.

Select **_Flutter_** SDK on this screen, the next screen is identical to the Android configuration screen. Running the same code for iOS will work without any further modifications.

![How to Add In-App Messages to a Flutter App](https://paper-attachments.dropbox.com/s_053EFD6140684D6BC9E1307180646321DDB0BC283990EAF5E7D6B91D562ECB7C_1647842248286_image.png)

At the bottom of the Apple iOS (APNs) Configuration screen, a warning will appear saying that your user has not subscribed. This is because we have not yet asked for permission to send push notification. We will be [asking for opt-in permission using in app messages](https://onesignal.com/blog/how-to-create-more-compelling-opt-in-messages-for-ios-push/) later in this article.

## Sending an In-App Message

Click on _ **Message** _ from the main navigation bar and then select _ **In-App** _ from the submenu that appears.

Onesignal provides default in-app messaging templates which can then be customized according to your use case and preference. From the list of templates, click on **_[Default Template] Welcome Message_**.

![How to Add In-App Messages to a Flutter App](https://lh4.googleusercontent.com/ZtKIq8Q5hxYuszQM_bH4Yf8LyDzVZsZgB3dMrfBkqx3gkPjkhDumAZwg5TERq4G_ezs-r4k-Eu9vjBwVyOu7cY-x6P3_SvKyQlOE14BT-4gA0ZaqZtPLim_I-aP10hy17lnW_o-r)

In the top right corner of the screen, select **_Actions_** — a drop-down menu will appear. If you'd like to edit and customize the default welcome message, click Edit to alter the template. If you've finished editing or would simply like to test the default message as is, click _ **Resume** _ from the drop-down menu. Then, run the app on your device.

![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/flutter-sending-in-app.jpg)

## In-App Messaging Triggers

You can use [Triggers](https://documentation.onesignal.com/docs/iam-triggers) to choose when to show the in-app message to the user. There are some predefined Triggers such as "app open," as well as custom triggers that can be set programmatically using the `addTrigger()` function. To begin, let's try using a predefined trigger for showing an app rating message.

If you're using a free OneSignal plan, you will only be able to have one in-app message live at a time. Before creating the new message, you'll need to pause the welcome in-app message by clicking _ **Actions** _ and then _ **Pause** _ from the drop-down menu. Then, navigate back to the main in-app messages screen and select **_[Default Template] App Store Rating_**. Select _ **Actions** _ > **_Edit_** and then scroll down on the editing screen to the section entitled **_3. Triggers_**.

![How to Add In-App Messages to a Flutter App](https://lh4.googleusercontent.com/F1o5vfGYugkkpPBcJoaGGVfhuSmaPdjEd1TkbUSpk-PmgAz9ivXwtK3jDelGDDxzx-os2pGc--S4ldpcUdJKmwjUplscPUaS_9l9VdrBp-Tea_xeGZZ5zD3FdkJOURk9rXi_GU72)

When should users see this message? select _ **When certain conditions are satisfied during the session** _. You should see two form fields for **_session duration_** and _ **duration since the last in-app** _. Enter a session duration greater than 10 seconds for demonstration purposes, then scroll down to the bottom of the page and click on the blue **_Update Message_** button.

![How to Add In-App Messages to a Flutter App](https://lh6.googleusercontent.com/JfiPv71jN9ad6eXNRlmIbd_RWTenYhSOiX6JI8265cwDjJhbeZ7ZHLiRckmlkzTtBPhM_MZOyXxAISjtTodSo3KBOhmZrrY37uVWIb-r2Wa3-IOsruDfKTzX4ckghxg0AwLds0OI)

Then, from the list of In-app messages, click _ **Actions** _ > _ **Resume** _ for this message and then open the app. After 10 seconds, you should see a rating request message inside your app.

![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/flutter-in-app-messaging-triggers.jpg)

This example demonstrates the power of in-app messaging! Using OneSignal's in-app messaging tool, you can:

- Add and remove in-app messages remotely without requiring any app update.
- Leverage useful, pre-made triggers such as _ **app open** _, **_session duration_** , and _ **duration since the last in-app message** _, along with the option to club these triggers with an OR operation. This makes implementing a wide range of in-app messaging strategies possible without requiring any code customizations!

### Asking for Push Permission (iOS)

In iOS, a user needs to grant permission to an app in order to receive push notifications. As a general rule of thumb, you don’t want to ask a user for push notification permission immediately when they first launch the app because they aren't likely to understand the value of notifications at that early stage of adoption. Onesignal provides a predefined in-app messaging template to help you [time your opt-in request and give users more context to inform th](https://onesignal.com/blog/how-to-create-more-compelling-opt-in-messages-for-ios-push/)eir opt-in decision.

To try out this prompt, pause the current message (if you're using a free account), then click **_Action_** > _ **Resume** _ to enable the _**[Default Template] Push Permission Prompt**_. This prompt has been set to show the user a message asking for permission upon launching the app, but the trigger and message content can be customized to provide a better user experience and increase the likelihood of opt-in.

![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/flutter-asking-for-push-permissions.jpg)

If the clicks to **_Allow_** notifications in the in-app message, it will automatically trigger the native iOS permission prompt. If they click **_Maybe Later_** , they will be opted out of notifications but can be prompted again later with an in-app message encouraging them to revisit this decision.

![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/flutter-push-notifications-permission-pop-up.jpg)

If a user denies permission to receive notifications the first time around, but later clicks _ **Allow** _ when they are re-prompted, they will be taken to the notification settings where they will have to manually allow the app to show notifications — this is a restriction imposed by iOS.

### Using Custom Triggers in In-App Messaging

Custom triggers are key-value pairs of string or integer types to which the SDK responds. Whenever the condition set is satisfied, the trigger is initiated. Custom triggers can be clubbed together with AND and OR to create more complex triggers.

For demonstration purposes, let’s build a button that, when tapped eight times, will trigger a promotional in-app message.

To do so, open `main.dart` and add a floating action button to the scaffold, along with a variable to save the button tap count.

```
void main() {
 runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);
 
 // This widget is the root of your application.
 @override
 Widget build(BuildContext context) {
   return const MaterialApp(
     home: MyHomePage(),
   );
 }
}
 
class MyHomePage extends StatefulWidget {
 const MyHomePage({Key? key}) : super(key: key);
 
 @override
 State<MyHomePage> createState() => _MyHomePageState();
}
 
class _MyHomePageState extends State<MyHomePage> {
 int taps = 0;
 
 @override
 void initState() {
   super.initState();
   initMessaging();
 }
 
 Future<void> initMessaging() async {
   await OneSignal.shared.setAppId("f3afbef4-2fe4-452b-a391-b8175c2b65a1");
 }
 
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: const Text('OneSignal IAM'),
     ),
     floatingActionButton: FloatingActionButton(
       onPressed: () {
         setState(() {
           taps = taps + 1;
         });
         OneSignal.shared.addTrigger('taps', taps);
       },
       child: const Icon(Icons.add),
     ),
     body: const Center(child: Text('IAM')),
   );
 }

```

Open the OneSignal dashboard, select the _**[Default Template] 10% Off Promotional**_ template, and click _ **Actions** _ > _ **Edit** _. On the editing page, scroll down until you see the **_3. Triggers_** section. Under the question, **_When should users see this message?_** select **_When certain conditions are satisfied during the session_**. Click **_IN-APP TRIGGER_** and input **_taps is 8_** to the appropriate form fields, as shown below.

![How to Add In-App Messages to a Flutter App](https://lh5.googleusercontent.com/FqsNq5n7ROCTM0b-uGsMMXftLnKgyXwvMA1yAQKLVjd2aae2v_o90yx5QHwB8OIT8VV-voQrXSikhU4N368zWtojvWs_kRwvVaX0s-YEivH2G5Qx2mnRvZryxDKMnZ2aEmNx7aPv)

Finally, click _ **Add Trigger** _ and then scroll to the bottom of the page and click **_Update Message_**. If you followed along and implemented the previous example, the push permission prompt will still be live. If you are using a free plan, pause that message, navigate back to your promotional message, and click **_Actions_** > **_Resume_** to set this one live. Now, run the app with the updated code. Tap the button 8 times and the promotional message should pop up on your screen.

![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/flutter-using-custom-triggers.jpg)

This custom trigger was an example of `key` is `value` pair. There are other conditions on which the triggers can be set as well.

![How to Add In-App Messages to a Flutter App](https://lh4.googleusercontent.com/1RHH9EqDClgKyMnlqql3-bPUYFdTk12FCVdYDn3hmk4AlFBwzZa09vIc-a0M4y4H3XbZ36D8d0b1__5bcCvm7KxKVDyHB36PGMWoNIdzMtVmOIGDS9S-ivbuUorFp9mNNTxqEQ16)

One of the best things about Onesignal's in-app messaging tool is the ability to overhaul the design of the popup without doing an app update. To demonstrate, let's update the current 10% promotional message to something more appropriate. To do so, first click _ **Actions** _ > **_Pause_** to pause the current message, then click on _ **Edit** _.

All the UI elements are highly customizable in the OneSignal message builder, as can be seen in the video below. Almost all aspects of text can be formatted to suit the design language of your app.

<!--kg-card-begin: html--><iframe width="560" height="315" src="https://www.youtube.com/embed/2rtoY29A_I8" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html-->

Messages also do not have to be fixed to a particular type of layout. All the UI elements can be reordered on the fly without requiring an app update.

<!--kg-card-begin: html--><iframe width="560" height="315" src="https://www.youtube.com/embed/jX1l3epR1aQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html-->

In-app messages also support GIFs!

<!--kg-card-begin: html--><iframe width="560" height="315" src="https://www.youtube.com/embed/s55nSv_llzc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html-->

Let’s apply all these changes, scroll to the bottom and click _ **Update Message** _. No need to update any code, just open the app again!

![How to Add In-App Messages to a Flutter App](https://onesignal.com/blog/content/images/2022/04/flutter-using-custom-triggers-gif--1--1.jpg)

## Adding Click Actions in Messages

Onesignal provides a handful of click actions out of the box that can be customized from the dashboard. There is also a Custom Action ID, in which a custom action ID string is sent, which can handle custom cases such as deep-linking, app updates, or any other functionality.

![How to Add In-App Messages to a Flutter App](https://paper-attachments.dropbox.com/s_053EFD6140684D6BC9E1307180646321DDB0BC283990EAF5E7D6B91D562ECB7C_1647766296013_image.png)

Let’s implement a URL click action first. Implementing an URL means that when a user clicks on the button, they will be taken to the specified URL. To add a link, click **_Actions_** > _ **Edit** _ on the promotional message (if you closed out from the last example) and scroll down to the _ **Button 1** _ box and update the URL. Then, scroll down to the bottom of the page and click _ **Update Message** _. Then, click _ **Action** _ > **_Resume_** to resume the message. To test it out, open your app and tap the button 8 times again.

![How to Add In-App Messages to a Flutter App](https://paper-attachments.dropbox.com/s_053EFD6140684D6BC9E1307180646321DDB0BC283990EAF5E7D6B91D562ECB7C_1647788200215_image.png)

Once the message pops up, press the first button and you should be taken to the website link you provided.

## Custom Click Action ( Custom Action ID)

Creating custom click actions requires developer support. All the use cases that may be necessary for the future should be listed beforehand and handled in the code.

In this example let’s try deep linking to a second page when pressing the button. To do so, create a new file called success\_screen.dart and add this code.

```
import 'package:flutter/material.dart';
class SuccessScreen extends StatelessWidget {
  const SuccessScreen({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
        child: Text(
          'Success',
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 42),
        ),
      ),
    );
  }

```

Now, go to the `initMessaging()` in `main.dart` and add a `setInAppMessageClickedHandler` to listen to any click actions that happen on the message.

```
 Future<void> initMessaging() async {
    await OneSignal.shared.setAppId("f3afbef4-2fe4-452b-a391-b8175c2b65a1");
    OneSignal.shared.setInAppMessageClickedHandler((action) {
      if (action.clickName == 'successPage') {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (_) => const SuccessScreen()));
      }
    });
  }

```

This works as follows:

- set `InAppMessageClickedHandler` listens to any action event that is emitted by interacting with any UI element.
- When a click action is set in the OneSignal console, it means that an action binds to that UI element.
- Whenever an interaction occurs with that element, the action is triggered.
- If that action is a pre-defined one, such as opening a URL, then while the click handler will listen to the action being emitted, the action to perform is already handled by the SDK and will result in opening the URL in the browser.
- For action IDs that you specify, you can build different use cases as shown in the above example to handle different action IDs.
- In the above snippet, the action [has many properties](https://documentation.onesignal.com/docs/iam-sdk-methods#in-app-message-click-handler) which can be further leveraged to create better user experiences.

Now, click **_Action_** > **_Pause_** to pause the current message and then select **_Edit_**. Scroll down to the button to which a click action has to be added. Then, select **_Custom Action ID_** and give the action a name such as **_successPage_**.

![How to Add In-App Messages to a Flutter App](https://paper-attachments.dropbox.com/s_053EFD6140684D6BC9E1307180646321DDB0BC283990EAF5E7D6B91D562ECB7C_1647787194459_image.png)

Next, scroll down to the bottom of the screen and click **_Update Message_** and **_Resume_** the message via the **_Actions_** menu. Now, run the updated app.

When you click on the button, you should have successfully implemented deep linking!

<!--kg-card-begin: html--><iframe width="560" height="315" src="https://www.youtube.com/embed/fU58LmmgpMM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><!--kg-card-end: html-->
## Share Your Feedback

We'd love to know what you think and answer any additional questions you have. To connect with us, [create an issue on GitHub](https://github.com/OneSignal/onesignal-vue/issues) or ping us on the [OneSignalDevs Discord server](https://discord.com/invite/EP7gf6Uz7G) to share your experience.  We appreciate any insight you can share to help us better serve Vue.js users!

To stay in the loop with the latest product updates and innovations, follow the [OneSignal Developers Twitter](https://twitter.com/onesignaldevs). For additional support and dev inspiration, tap into our global developer community.

### **>> [Connect with the OneSignal Developer Community](https://onesignal.com/onesignal-developers)**

###   
_This guest post was authored by Chinmay Kabi_