How to migrate data from react native asyncstorage to flutter?

860

Solution 1

After facing the same problem today, I've come up with a solution for iOS. I don't have an issue on Android so unfortunately I don't have a solution for Android either. Basically the RN AsyncStorage package creates a folder that includes a manifest.json. This folder is stored in the Documents directory of your app. My approach is to simply load that file and return the key.

Future<String> getReactNativeAsyncStorageValue(String key) async {
  if (!Platform.isIOS) return null;
  try {
    Directory directory = await getApplicationDocumentsDirectory();
    Directory rctStorageDirectory = Directory(directory.path + '/RCTAsyncLocalStorage_V1');
    File manifest = File(rctStorageDirectory.path + "/manifest.json");
    if (await rctStorageDirectory.exists() && await manifest.exists()) {
      try {
        String data = await rootBundle.loadString(manifest.path);
        if (data?.isNotEmpty ?? false) {
          var jsonData = json.decode(data);
          if (jsonData is Map) {
            String value = jsonData[key];
            if (value != null) {
              return value;
            }
          }
        }
      } catch (error) {
        print(error);
      }
    }
  } catch(error){
    print(error);
  }
  return null;
}

Solution 2

i did the same thing, and ended up making a simple helper class with flutter_secure_storage:

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

class LocalStorage {

  final storage = new FlutterSecureStorage();

  void writeValue(String key, String value) {
    storage.write(key: key, value: value);
  }

  void deleteValue(String key) async {
    await storage.delete(key: key);
  }

  Future readValue(String key) async {
    String value = await storage.read(key: key);
    return value;
  }

}

which you'd then use in a screen like so:

final _storage = new LocalStorage();

Future _getValue() async {
  String _someValue = await _storage.readValue('someKey');
}
Share:
860
Ricardo Mendieta
Author by

Ricardo Mendieta

Updated on December 06, 2022

Comments

  • Ricardo Mendieta
    Ricardo Mendieta 12 months

    I'm looking to migrate a react native app to flutter, so far everything is good. But I have to migrate user data stored in react native asyncstorage and I don't even know where to start. Does anyone can guide me in the right direction?

    • Florian
      Florian almost 3 years
      Ricardo - did you find a solution for this? I have the same problem
  • Ricardo Mendieta
    Ricardo Mendieta over 5 years
    this works for new data added to the storage, what im looking for is to retrieve de data stored on the react native app. I already have the app released and want to migrate to flutter.