title: Flutter - FCM: how to store background message to SQLite
body: <p>I am building a notification system for my mobile application, the idea is to store both foreground and background messages received from Firebase Cloud message to SQLite. I've followed the <a href="https://pub.dev/packages/firebase_messaging" rel="nofollow noreferrer">guideline</a> here to set up my project.</p>
  
  <p>Here my code:</p>
  
  <pre><code>void initState() {
      super.initState();
      service = MySQLService();
  
      _firebaseMessaging.configure(
        onMessage: (Map&lt;String, dynamic&gt; message) async {
          print("onMessage: $message");
          service.insertItem(Item.fromMessage(message)); // It's working, here.
        },
        onBackgroundMessage: myBackgroundMessageHandler,
        onLaunch: (Map&lt;String, dynamic&gt; message) async {
          print("onLaunch: $message");
        },
        onResume: (Map&lt;String, dynamic&gt; message) async {
          print("onResume: $message");
        },
      );
  
      _firebaseMessaging.requestNotificationPermissions(
          const IosNotificationSettings(
              sound: true, badge: true, alert: true, provisional: true));
      _firebaseMessaging.onIosSettingsRegistered
          .listen((IosNotificationSettings settings) {
        print("Settings registered: $settings");
      });
      _firebaseMessaging.getToken().then((String token) {
        assert(token != null);
        print("Push Messaging token: $token");
      });
  }
  </code></pre>
  
  <p>And the code for handling background message:</p>
  
  <pre><code>Future&lt;dynamic&gt; myBackgroundMessageHandler(Map&lt;String, dynamic&gt; message) async {
    print("onBackground: $message");
    var service = MySQLService();
    await service.insertItem(Item.fromMessage(message)); // It's not working, here.
    return Future&lt;void&gt;.value();
  }
  </code></pre>
  
  <p>For now, my application can: receive foreground message and store it into SQLite (by calling <strong>service.insertItem</strong>), But for some reason, background message is not stored in the SQLite even it displayed on the notification list of the device.</p>
  
  <p><a href="https://i.stack.imgur.com/Yi5Ud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yi5Ud.png" alt="enter image description here"></a></p>
  
  <p>UPDATE: here the code for inserting message</p>
  
  <pre><code>  Future&lt;void&gt; insertItem(Item notification) async {
      final Database db = await MyDatabase.getDatabase();
      await db.insert('notification', notification.toMap(),
          conflictAlgorithm: ConflictAlgorithm.replace);
      return Future&lt;void&gt;.value();
    }
  </code></pre>