Implementing In-App Messaging with Flutter and Firebase

In-app messaging is a powerful tool to engage users, provide contextual information, and promote features within your Flutter application. By integrating Firebase In-App Messaging (FIAM), you can easily deliver targeted and customizable messages to your users while they’re actively using your app. This article provides a comprehensive guide on how to implement in-app messaging in your Flutter application using Firebase.

What is Firebase In-App Messaging?

Firebase In-App Messaging (FIAM) is a service provided by Firebase that allows you to send targeted and contextual messages to users while they’re using your app. These messages can be used for a variety of purposes, such as announcing new features, providing promotions, offering tutorials, and prompting users to take specific actions. FIAM messages can be triggered based on user behavior, app usage, or custom events, making them highly effective and relevant.

Why Use Firebase In-App Messaging?

  • Engage Users: Send relevant messages to keep users engaged and informed.
  • Contextual Messaging: Deliver messages based on user behavior and app context.
  • Customizable Campaigns: Create personalized messages with flexible targeting options.
  • Integration with Firebase: Seamless integration with other Firebase services.

Prerequisites

Before you start, make sure you have the following prerequisites:

  • A Flutter project set up and running.
  • A Firebase project created in the Firebase Console.
  • Firebase configured for your Flutter app (including the firebase_core plugin).

Step-by-Step Implementation

Follow these steps to implement in-app messaging in your Flutter app:

Step 1: Add Firebase In-App Messaging Dependency

Add the firebase_in_app_messaging plugin to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^2.15.0
  firebase_in_app_messaging: ^0.7.0+14

Run flutter pub get to install the dependencies.

Step 2: Initialize Firebase

Ensure Firebase is initialized in your main.dart file. If you haven’t already done so, add the following code:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase In-App Messaging Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Firebase In-App Messaging Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Check for In-App Messages!',
            ),
          ],
        ),
      ),
    );
  }
}

Step 3: Enable Firebase In-App Messaging

No specific code is needed in your Flutter app to enable FIAM after adding the dependency. Firebase In-App Messaging should start displaying messages once the app is running and the conditions for a campaign are met. To create these campaigns, navigate to your Firebase Console.

Step 4: Create an In-App Messaging Campaign in Firebase Console

To send messages to your users, you need to create campaigns in the Firebase Console:

  1. Go to the Firebase Console.
  2. Select your project.
  3. In the left-hand menu, navigate to Engage > In-App Messaging.
  4. Click on Create Campaign.
    • Fill in the campaign details:
      • Message: Choose the appearance of your message (modal, top banner, card, image only).
      • Target: Define who should see this message based on app, app version, and audience.
      • Schedule: Define when the message should be displayed.
      • Behavior: Set the event to trigger the message and add additional parameters if needed.
  5. Set your targeting conditions, schedule, and message behavior as per your requirements.
  6. Review and publish the campaign.

Common campaign configuration settings include:

  • Message Type (Modal, Image, Top Banner, Card).
  • Target Users by app version, demographic and behavioral attributes
  • Set triggers to display messages when a certain event happens, when the app is opened, etc.

Step 5: Triggering Events

Firebase In-App Messaging messages are often triggered based on events. FIAM can automatically trigger messages on app_open, but we often want to manually trigger based on a specific action. This requires calling `FirebaseInAppMessaging.instance.triggerEvent(“your_event_name”)`

Below example shows how to trigger the in app message via Button:

import 'package:firebase_in_app_messaging/firebase_in_app_messaging.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Firebase In-App Messaging Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Firebase In-App Messaging Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  void triggerInAppMessage() {
    FirebaseInAppMessaging.instance.triggerEvent('custom_event');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Tap the button below to trigger the in-app message',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: triggerInAppMessage,
              child: Text('Trigger Message'),
            ),
          ],
        ),
      ),
    );
  }
}

Step 6: Testing In-App Messaging

To test your in-app messaging implementation:

  1. Increase the frequency of test devices displaying messages.
  2. Add your device as a test device in Firebase Console.
  3. Run the application in debug mode.
  4. Trigger the events or conditions you’ve set in your campaign.

Step 7: Personalizing Messages (Optional)

FIAM allows personalization by using user properties. Firebase automatically provides standard properties such as app version and language, and allows to define custom events and custom user properties in your firebase project that can also be utilized.

Best Practices

  • Be Contextual: Ensure your messages are relevant to the user’s current activity in the app.
  • Don’t Overdo It: Avoid bombarding users with too many messages. Frequency capping can help with this.
  • Personalize: Use user properties to create more personalized messages.
  • A/B Testing: Experiment with different message types and triggers to optimize engagement.

Conclusion

Implementing in-app messaging with Flutter and Firebase can significantly improve user engagement and provide contextual support. By following these steps, you can easily integrate FIAM into your Flutter application, create targeted campaigns, and enhance the user experience.