7

I have an iOS app already on Store, Now planning to replace it with Flutter with new version release.

I want to get access native app's UserDefaults data in Flutter code.

Using the way suggested in Flutter docs I m getting null value. What I have tried is:

In my pubspec.yaml file :

dependencies:
  shared_preferences: ^0.5.12+4

Im my home.dart class file I'm importing header :

import 'package:shared_preferences/shared_preferences.dart';

And this is how I m trying to access data stored in iOS app from native app, I m using same bundle ID (Package ID) in flutter project to overwrite the app and it is successfully overwriting.

@override
void initState() {
    super.initState();
    getFromLocalMemory('user').then((value) =>
      userInfo = value
  );
}



Future<String> getFromLocalMemory(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String user = prefs.getString(key);
    return user;
}

It always returns null. While 'user' key has data when getting from iOS native app.

Adel B-Lahlouh
  • 1,059
  • 1
  • 8
  • 20
M Zubair Shamshad
  • 2,741
  • 3
  • 23
  • 45

2 Answers2

3

We can use existing plugin native_shared_preferences. It allows us to access native SharedPreferences on Android and UserDefaults on iOS. Sample code to read a value by key "SomeKey":

final someKey = "SomeKey";
var prefs = await NativeSharedPreferences.getInstance();
if (prefs.containsKey(someKey)) {
    print("Value for SomeKey: ${prefs.get(someKey)}");
}
Sergio
  • 27,326
  • 8
  • 128
  • 149
1

In that case, I suggest you use platform channel method

platform channels

iOS doesn't seem to allow flutter framework to access NSUserDefaults, when it didn't create it from the beginning,..

I hope it will work for you.

Sadeny Alpha
  • 386
  • 1
  • 7