Skip to content

[shared_preferences] Document the need to use reload when using multiple isolates or engines #101691

@Julianlu1

Description

@Julianlu1

I am working on this Flutter app and I have implemented Firebase Cloud Messaging. I added the following code to make sure I can use the Shared Preferences package. It seems to work, but the functionality does not work correctly.

if (Platform.isAndroid) SharedPreferencesAndroid.registerWith();
  if (Platform.isIOS) SharedPreferencesIOS.registerWith();

The backgroundhandler in action:

Future<void> backgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  if (Platform.isAndroid) SharedPreferencesAndroid.registerWith();
  if (Platform.isIOS) SharedPreferencesIOS.registerWith();
  print("App is in background: Message received ");

 String productId = message.data['productId'];
 SendPort mainToIsolateStream = (await initIsolate()) as SendPort;
  final prefs = await SharedPreferences.getInstance();

  final listOfTopics = prefs.getStringList('out_of_stock_topics') ?? [];
  print('BEFORE unsubscribe, print list of topics: $listOfTopics');
  // Returns locale string in 'en_US'
  // String defaultLocale = Platform.localeName;
  String defaultLocale = prefs.getString('language') ?? "";
  String topic = '${productId}_$defaultLocale';
  print('The topic: ${topic}');
  print("The list of topics: ${listOfTopics}");
  // Check if topic already exists
  if (listOfTopics.contains(topic)) {
    print("Topic deleted");
    LocalNotificationService.unsubscribeToTopic(topic);
    listOfTopics.remove(topic);
    print(listOfTopics.length);
    await prefs.setStringList('out_of_stock_topics', listOfTopics);
  }
}

The code above deletes the topic in the list. Then the list is set with prefs.setStringList. I checked, and the code goes into the if statement. It removes the item from the list. But something goes wrong in prefs.setStringList I suppose.

Because later I use the following code to check the items in the 'out_of_stock_topics' list.

 final prefs = await SharedPreferences.getInstance();
                final listOfTopics =
                    prefs.getStringList('out_of_stock_topics') ?? [];
                print(listOfTopics);

But the topic is not correctly deleted and is still there. I think there is something wrong in the backend of the backgroundhandler. I tested this feature with 2 buttons: "add topic" and "delete topic". And with those separate buttons it does delete the item from the 'out_of_stock_topics' list.

Does anyone know how to fix this problem?
Thanks!

Metadata

Metadata

Labels

P2Important issues not at the top of the work listp: shared_preferencesPlugin to read and write Shared Preferencespackageflutter/packages repository. See also p: labels.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions