23

I am using FlutterSecureStorage to store certain items, namely the API tokens to access server side resources. However, I've run into a weird issue. I had to delete the database (as I'm still in testing mode, this happens quite frequently for now), which deleted all the tokens as well. But when the app tries to connect it gets an error.

On Android, this is not a big deal. I just uninstall and reinstall the app and it will download a fresh token.

On iOS, there's a problem. Because FlutterSecureStorage stores any info in the keychain, the data doesn't get deleted even if the app is uninstalled. So after i reinstall it, it still gets the token from storage, and I can't refresh the token.

My question is: Is there some way to run code to remove all Storage items during install or uninstall in Flutter?

starman1979
  • 724
  • 4
  • 8
  • 31

1 Answers1

45

On iOS you can make use of NSUserDefaults, which does get deleted on an app uninstall. That way you can perform a check whether the app is starting for the first time after an uninstall. Use the shared_preferences Flutter plugin to make use of NSUserDefaults.

This approach has been discussed on StackOverflow for other platforms before, see Delete keychain items when an app is uninstalled for examples in other languages.

For Flutter this example would become:

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';

// ...

final prefs = await SharedPreferences.getInstance();

if (prefs.getBool('first_run') ?? true) {
  FlutterSecureStorage storage = FlutterSecureStorage();

  await storage.deleteAll();

  prefs.setBool('first_run', false);
}
Tim Klingeleers
  • 2,344
  • 13
  • 19