2

I am saving modal object converted into String to SharedPreference and Killing the app. But when I come back to app SharedPreference has lost the saved data. I am new to flutter. Please help. I want to save my data and kill the app and again retrieve while coming back.

Here is my code

    class HomeScreen extends StatefulWidget {
       HomeScreen({Key? key}) : super(key: key);
       @override
       State<HomeScreen> createState() => _HomeScreenState();
    }

     class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
        List<User> selectedUser = [];
        List<User> visibleUser = [];
        double screenHeight = 0.0;
        static const _keyUser = 'users';

        @override
        initState() {
          super.initState();
          WidgetsBinding.instance!.addObserver(this);
          getUsersFromSharedPref();
        }

       Future<void> getUsersFromSharedPref() async {
         final pref = await SharedPreferences.getInstance();
         setState((){
           String savedJson = pref.getString(_keyUser) ?? '';
           if(savedJson.length > 0) {
              selectedUser = UserApi.getUsersFromSharedPref(savedJson);
           }
         });
       }

       Future<void> saveInSharedPref() async {
         final pref = await SharedPreferences.getInstance();
         String encodedData = UserApi.getStringFromobject(selectedUser);
         await pref.setString(_keyUser , encodedData);
       }

       @override
       Widget build(BuildContext context) {
         return Scaffold(
            body: FutureBuilder<List<User>>(
            future: UserApi.getUserLocally(context),
            builder: (context, snapshot) {
            final allUsers = (selectedUser.isNotEmpty) ? selectedUser : snapshot.data;
            visibleUser = (selectedUser.isNotEmpty)?(selectedUser.where((aUser) => (aUser.isDefaultUser)).toList()) : (allUser!.where((aUser) => (aUser.isDefaultUser)).toList());
            .
            .
            .
            })
         );
     }

     @override
     void dispose() {
        super.dispose();
     }

     @override
     void didChangeAppLifecycleState(AppLifecycleState state) {
        super.didChangeAppLifecycleState(state);


     final isBackground = state == AppLifecycleState.paused;

     if (isBackground || (state == AppLifecycleState.inactive ||
          state == AppLifecycleState.detached)) {
          saveInSharedPref();
     }

     if(state == AppLifecycleState.resumed){
          getUserFromSharedPref();
     }
     }
   }



  class UserApi {
      static Future<List<User>> getUserLocally(BuildContext context) async {
           final assetBundle = DefaultAssetBundle.of(context);
           final data = await assetBundle.loadString('assets/data/Users.json');
           final body = json.decode(data.toString()).cast<Map<String, dynamic>>();
           return body.map<User>((json) => new User.fromJson(json)).toList();
      }

      static List<User> getUserFromSharedPref(String jsonString){
          final body = json.decode(jsonString).cast<Map<String, dynamic>>();
          return body.map<User>((json) => new User.fromJson(json)).toList();
      }
  }

I am not getting saved data after killing the app from SharedPreferences.

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Juno
  • 347
  • 2
  • 11
  • I think you are misinterpreting about application states (kill app != in background...). Why don't you save selected user data as soon as you choose it? – Kien Vu Dec 08 '21 at 12:04
  • But is AppLifecycleState.detached not for killing the app? Just a query. Though I am trying now to save on selection. Thanks – Juno Dec 08 '21 at 18:47

0 Answers0