swiftflutteruserdefaultswidgetkit

how to access shared_preferences stored in flutter inside swiftui widget


I have a flutter app in which I have set shared_preferences, now I am creating a widget which is then done in native using swiftUI and WidgetKit. however now I am stuck at how to get the value of preferences which I stored in flutter as I have searched that flutter shared_preferences stores it in swiftUI UserDefaults. I have tried different solutions but still no luck, follows what I have tried:

1- I have set app group in both app and widget then I have used it like this, note I am calling this inside widget TimelineProvider getTimeline() function.

let defaults = UserDefaults(suiteName: "app.group.id")
    let value = defaults?.object(forKey: "flutter.KEY")
    print("-- Here \(value ?? "empty")")

2- I have done same approach with using standard instead of group id.

also some other minor tweaks which I think will work but no progress. I am new to swift as this is my first project on it so I am making some mistake but don't know what kindly any help would be appreciated.


Solution

  • After trying almost everything, I have found a reason why my userdefaults is not giving me data stored in flutter shared_preferences. It is because flutter shared_preferences uses userdefault.standard when storing/setting data hence in my widget it is not available even though I have given both target (App and widget) same group Id is because of this as my flutter Shared_pref package is setting it on standard. To fix this I have applied different approach I have used this Package it allows me to set appGroup inside flutter when then I can use to get value in my swiftUi widget. In background this package uses methodChannels which are used to call a method from flutter to directly set appGroup and values in swiftUi userdefaults. this is my approach and I dont know if it is correct or not as I am new to swift but it works for now.