Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter SharedPreference do not persist

I want to save user preferences using Flutter's SharedPreference. But the registered preferences are ALL null at new start (when app have been closed, not unistalled).

settings.dart :

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SettingsPage extends StatefulWidget{

  @override
  _SettingsPageState createState() => new _SettingsPageState();

}

class _SettingsPageState extends State<SettingsPage>{

  bool _param1IsON;
  bool _param2IsON;
  bool _param3IsON;

  @override
  void initState() {
    super.initState();
    _param1IsON = false;
    _param2IsON = false;
    _param3IsON = false;
    loadPreferences();
  }

  Future<Null> loadPreferences() async {
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    if(_preferences.getBool('setted') == null || !_preferences.getBool('setted'))
      SharedPreferences.setMockInitialValues({}); // Library fix line

    bool param1IsON = _preferences.getBool('param1IsON');
    bool param2IsON = _preferences.getBool('param2IsON');
    bool param3IsON = _preferences.getBool('param3IsON');
    setState(() {
      _param1IsON = (param1IsON != null)? param1IsON : _param1IsON;
      _param2IsON = (param2IsON != null)? param2IsON : _param2IsON;
      _param3IsON = (param3IsON != null)? param3IsON : _param3IsON;
    });
    _preferences.setBool('setted', true);
  }

  Future<Null> setBoolSettings(String key, bool value) async {
    switch(key){
      case 'param1IsON':
        setState(() {
          _param1IsON = value;
        });
        break;
      case 'param2IsON':
        setState(() {
          _param2IsON = value;
        });
        break;
      case 'param3IsON':
        setState(() {
          _param3IsON = value;
        });
        break;
      default:
        print("Unknown settings '$key'");
    }
    SharedPreferences _preferences = await SharedPreferences.getInstance();
    await _preferences.setBool(key, value);
  }

  @override
  Widget build(BuildContext context) {
    return new ListView(
        children: <Widget>[
          new ListTile(
            title: new Text(Param 1'),
            trailing: new Switch(value: _param1IsON,
              onChanged: (bool newValue) {
                setBoolSettings('param1IsON', newValue);
              }),
          ),
          new ListTile(
            title: new Text('Param 2'),
            trailing: new Switch(value: _param2IsON,
              onChanged: (bool newValue) {
                setBoolSettings('param2IsON', newValue);
            }),
          ),
          new ListTile(
            title: new Text('Param 3'),
            trailing: new Switch(value: _param3IsON,
              onChanged:
                (bool newValue) {
                  setBoolSettings('param3IsON', newValue);
            }),
          ),
        ]
      );
  }
}

What I get:

At lunch 3 parameters are false. If I turn 'ON' one of them, wait 2s (it is not an async problem), then close the app and Start again... All of my parameters are false.

What I want:

At lunch 3 parameters are false. I turn 'ON' one of them. I close the app. Start again. The previous param I turned 'ON' is still true.

like image 890
Jérémy Avatar asked Feb 04 '19 20:02

Jérémy


People also ask

How do you store key-value pairs in Flutter?

How does Flutter store key-value data? If you have a relatively small collection of key-values to save, you can use the shared_preferences plugin. Normally, you would have to write native platform integrations for storing data on both iOS and Android.

How remove data from SharedPreferences in Flutter?

To remove data from the SharedPreferences, we'll use the remove method. The key of the data is passed to the . remove method so the key-value pair data in the SharedPreferences is deleted.


2 Answers

I had the same issue and fixed it in Android/../MainActivity.java by adding at the top:

import io.flutter.plugins.GeneratedPluginRegistrant;

As well as under super.onCreate(savedInstanceState);

GeneratedPluginRegistrant.registerWith(this);

The problem comes from using

SharedPreferences.setMockInitialValues({}); 

I got it from Flutter Test MissingPluginException but it seems to clear all the shared preferences.

However if you remove SharedPreferences.setMockInitialValues({}); and you don't have the two lines above in MainActivity.java, you'll get:

MissingPluginException(No implementation found for method getAll on channel flutter: plugins.flutter.io/shared_preferences)

I hope it helps!

like image 105
jeangali Avatar answered Oct 27 '22 11:10

jeangali


Hi I also faced the same issue. Did so many things. nothing helped .This may help someone.First thing ,followed this url and did the changes

1.https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects

2.Run the command flutter upgrade

3.Changed the shared preferences plugin in pubspec.yaml file

shared_preferences: ">=0.5.10 <2.0.0"

4.Deleted the pub cache from installed flutter location

C:\Users\myuser\AppData\Local\Pub\Cache\hosted\pub.dartlang.org

5.flutter build apk --debug

6.flutter build apk --profile

7.flutter run --release (if I run directly this command its throwing error like debug.jar not found , so I ran command 5 and 6 )

Command 7 is for - To Verify whether its working perfectly in release mode.

Finally I tried to generate app build without shrinking the code. then it worked

flutter build apk --no-shrink flutter build appbundle --no-shrink

like image 23
Saranya Subramanian Avatar answered Oct 27 '22 10:10

Saranya Subramanian