MoEngage Integration for Flutter
Integrating MoEngage into Your Flutter App
A complete, beginner-friendly walkthrough covering SDK setup, push notifications, in-app messaging, and event tracking.
MoEngage is a powerful customer engagement platform that lets you send personalized push notifications, in-app messages, and track user behaviour — all from a single dashboard. In this guide, you'll learn step-by-step how to integrate MoEngage into a Flutter project from scratch, even if you've never done it before.
SDK Setup
Install and configure the MoEngage Flutter plugin
Push Notifications
Send targeted push messages to Android & iOS
In-App Messaging
Show rich messages inside your running app
Event Tracking
Capture user actions for smart segmentation
📋 Table of Contents
Prerequisites
Before you start, make sure you have the following ready:
Flutter SDK Installed
Flutter 3.0+ is recommended. Run flutter --version to check.
MoEngage Account
Create a free account at app.moengage.com and note your APP ID from the dashboard.
Firebase Project (for Push)
Push notifications require Firebase. Set up a project at console.firebase.google.com and download google-services.json (Android) and GoogleService-Info.plist (iOS).
Xcode (for iOS)
iOS development requires Xcode 14+ on a Mac. Make sure you have an Apple Developer account.
SDK Setup & Installation
MoEngage provides an official Flutter plugin. Add it to your project's pubspec.yaml:
# pubspec.yaml dependencies: flutter: sdk: flutter # MoEngage core plugin moengage_flutter: ^8.0.0 # Required for push notifications via Firebase firebase_core: ^2.24.0 firebase_messaging: ^14.7.0
After editing, run the install command in your terminal:
flutter pub get
Android Configuration
2.1 — Add Google Services Plugin
Open android/build.gradle and add the Google Services classpath:
buildscript { dependencies { classpath 'com.google.gms:google-services:4.4.0' // MoEngage SDK dependency classpath 'com.moengage:moe-android-sdk:12.9.00' } }
2.2 — Apply Plugin in App Module
Open android/app/build.gradle and apply the Google Services plugin:
apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // ADD THIS android { defaultConfig { minSdkVersion 21 // Minimum required by MoEngage targetSdkVersion 34 } }
2.3 — Place google-services.json
Copy google-services.json (downloaded from Firebase Console) into the android/app/ folder.
package_name in your Firebase project matches applicationId in build.gradle, otherwise Firebase won't connect.iOS Configuration
3.1 — Install CocoaPods Dependencies
Navigate to the ios/ folder and run:
cd ios
pod install
3.2 — Add GoogleService-Info.plist
Drag GoogleService-Info.plist into your Xcode project under the Runner target. Make sure "Copy items if needed" is checked.
3.3 — Enable Push Capability in Xcode
Open Xcode
Open ios/Runner.xcworkspace in Xcode (not .xcodeproj).
Add Capability
Go to Runner → Signing & Capabilities → + Capability and add Push Notifications.
Background Modes
Also add Background Modes and enable Remote notifications and Background fetch.
SDK Initialization
Now that the native setup is complete, initialize MoEngage in your Flutter app. Open lib/main.dart:
import 'package:flutter/material.dart'; import 'package:moengage_flutter/moengage_flutter.dart'; import 'package:firebase_core/firebase_core.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // 1. Initialize Firebase first await Firebase.initializeApp(); // 2. Initialize MoEngage with your App ID final moengageInstance = MoEngageFlutter( 'YOUR_MOENGAGE_APP_ID', // Replace with your App ID ); moengageInstance.initialise(); runApp(MyApp()); }
Verify Initialization
Run your app with flutter run. If everything is set up correctly, you should see your device appear in MoEngage Dashboard → Audience → Active Users within a few minutes.
Push Notifications
Push notifications let you re-engage users even when the app is closed. MoEngage handles delivery; Firebase handles the token.
6.1 — Request Permission (iOS)
On iOS, you must explicitly ask the user for permission. Add this after initialization:
import 'package:firebase_messaging/firebase_messaging.dart'; Future<void> requestPushPermission() async { FirebaseMessaging messaging = FirebaseMessaging.instance; NotificationSettings settings = await messaging.requestPermission( alert: true, badge: true, sound: true, ); if (settings.authorizationStatus == AuthorizationStatus.authorized) { print('Push permission granted ✅'); } else { print('Push permission denied ❌'); } }
6.2 — Register FCM Token with MoEngage
MoEngage needs the Firebase Cloud Messaging (FCM) token to deliver pushes. Pass it like this:
Future<void> registerToken(MoEngageFlutter moengageInstance) async { String? token = await FirebaseMessaging.instance.getToken(); if (token != null) { // Pass token to MoEngage moengageInstance.passFCMPushToken(token); print('FCM Token registered: $token'); } // Listen for token refresh FirebaseMessaging.instance.onTokenRefresh.listen((newToken) { moengageInstance.passFCMPushToken(newToken); }); }
6.3 — Handle Push in Background
Add a top-level background handler (must be outside any class):
// Top-level function — NOT inside a class @pragma('vm:entry-point') Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async { await Firebase.initializeApp(); print('Background push received: ${message.messageId}'); } // Register in main() FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
In-App Messaging
In-app messages appear while the user is actively using your app — as banners, full-screen modals, or slides. No extra permissions needed.
7.1 — Show In-App Messages
MoEngage automatically shows in-app messages when triggered. You can also manually trigger them on specific screens:
// Show an in-app message on the current screen moengageInstance.showInApp(); // OR trigger a specific in-app campaign by its trigger name moengageInstance.showInApp( inAppCampaign: 'welcome_screen_popup', );
7.2 — Handle In-App Click Callbacks
You can listen for when a user clicks an in-app message button:
moengageInstance.setInAppMessageClickHandler( (InAppMessage message) { print('In-app clicked. Action: ${message.action}'); if (message.action == 'navigate') { // Navigate to a specific screen in your app Navigator.pushNamed(context, message.actionUri!); } } );
In-App Message Types Available
| Type | Description | Best Used For |
|---|---|---|
| Full Screen | Takes over the entire screen | Onboarding, major announcements |
| Modal / Popup | Centered overlay with dismiss option | Promotions, survey prompts |
| Slide-Up Banner | Appears from bottom of screen | Non-intrusive tips, alerts |
| Custom HTML | Fully custom HTML content | Rich media, interactive content |
Analytics & Event Tracking
Tracking events lets MoEngage build user segments so you can send the right message to the right person. There are two types: User Attributes and Custom Events.
8.1 — Track User Attributes
Set attributes on the user profile (name, email, etc.):
// Identify the user (call after login) moengageInstance.setUniqueId('user_12345'); // Set standard attributes moengageInstance.setUserName('Jane Doe'); moengageInstance.setEmail('jane@example.com'); moengageInstance.setPhoneNumber('+919876543210'); moengageInstance.setGender(MoEGender.female); // Set custom attributes moengageInstance.setUserAttribute('plan_type', 'premium'); moengageInstance.setUserAttribute('loyalty_points', 450);
8.2 — Track Custom Events
Events represent actions users take in your app:
// Simple event with no properties moengageInstance.trackEvent('App Opened', null); // Event with properties MoEProperties purchaseProps = MoEProperties() ..addAttribute('product_id', 'SKU-001') ..addAttribute('product_name', 'Blue T-Shirt') ..addAttribute('price', 29.99) ..addAttribute('currency', 'USD') ..addAttribute('is_sale_item', true); moengageInstance.trackEvent('Product Purchased', purchaseProps);
8.3 — Reset on Logout
When the user logs out, always reset MoEngage to clear the user session:
// Call this during logout flow void onLogout() { moengageInstance.logout(); print('MoEngage session cleared.'); }
setUniqueId() after login and logout() after sign-out. This ensures analytics and campaigns are correctly attributed to the right user.Common Events to Track
| Event Name | When to Trigger | Example Properties |
|---|---|---|
User Signed Up |
After successful registration | signup_method, referral_code |
Product Viewed |
When a product detail page opens | product_id, category, price |
Add To Cart |
When item added to cart | product_id, quantity, price |
Order Completed |
After payment success | order_id, total_amount, items |
Search Performed |
When user submits search | search_term, results_count |
You're All Set!
You've successfully integrated MoEngage into your Flutter app. Here's a summary of everything covered:
SDK Installed
moengage_flutter added to pubspec.yaml and initialized in main.dart.
Push Notifications Ready
FCM token registered, permissions requested, background handler added.
In-App Messaging Active
Messages show automatically or on manual trigger. Click handlers added.
Events & Attributes Tracked
User identity, attributes, and custom events flowing to MoEngage dashboard.
Comments
Post a Comment