Search code examples
dartfluttersharedpreferences

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.


Solution

  • 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!