MoneyBall
MoneyBall

Reputation: 2563

flutter global variable becomes null when app is in background

I have a messaging app that receives push notification from Firebase Cloud Messaging and when it does, it pushes it to a stream. In order to keep track of different streams, I have a streamtable which is a global variable. This is what I have

Map<String, StreamController<dynamic>> streamtable;

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
  log('FCM onBackground: $message');
  log('streamTable: $streamtable');
  addToStream(message);
  await showNotification(message);
  return;
}

bool addToStream(Map<String, dynamic> message) {

  var data;
  if (Platform.isAndroid) {
    data = message['data'];
  } else if (Platform.isIOS) {
    data = message;
  }

  bool status;
  try {
    switch (data['streamType']) {
      case "Message":
        streamtable['MessageStream'].add(message);
        status = true;
        break;
      default:
        log("streamType: ${data['streamType']}");
        status = false;
        break;
    }
  } catch (e) {
    status = false;
    log('addToStream: error($e)');
  }
  return status;
}

When the app is in the foreground, everything works great. However, when the app is in the background, streamtable becomes null, and nothing works.

  1. First off, why is that happening? If I bring the app back to foreground, streamtable is not null.
  2. How do I store data I receive when the app is in the background?

Upvotes: 1

Views: 1407

Answers (2)

nvoigt
nvoigt

Reputation: 77285

Mobile systems work differently than desktop systems. For desktop systems, "in the background" just means the UI is not on top, but the program is running. For mobile systems, "in the background" means the app is not used and as such can be killed by the operating system any time it sees fit.

Different systems have different callbacks to notify the app of impeding shutdown so it can write it's last data to a storage and restore from that state when it's called again.

The thought that your app holds global data and retains it in memory, since it's running, just "in the background" is not correct. It won't. It can be gone any time on mobile systems.

You will need to actually save the data you want to restore later, the "memory" only lasts as long as it's in the foreground or the operating system feels generous.

Upvotes: 2

MoneyBall
MoneyBall

Reputation: 2563

Seems like it's a bug in flutter: (https://github.com/FirebaseExtended/flutterfire/issues/1878)

Upvotes: 0

Related Questions