Jérémy
Jérémy

Reputation: 1890

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.

Upvotes: 10

Views: 10267

Answers (2)

Saranya Subramanian
Saranya Subramanian

Reputation: 461

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

Upvotes: 1

jeangali
jeangali

Reputation: 322

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!

Upvotes: 6

Related Questions