Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

dart - 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?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...