10

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.

Jérémy
  • 1,790
  • 1
  • 24
  • 40
  • "[Flutter: Shared Preferences null on Startup](https://stackoverflow.com/questions/49957815/flutter-shared-preferences-null-on-startup)" did not work for me. "[shared preference is deleted when application is closed](https://stackoverflow.com/questions/52321462/shared-preference-is-deleted-when-application-is-closed)" neither. – Jérémy Feb 04 '19 at 20:36

2 Answers2

6

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!

jeangali
  • 312
  • 1
  • 6
  • 1
    Can you help me with this issue ? I already have that 2 lines in my MainActivity still my sharedpreference is empty on startup and I didn't find this line `SharedPreferences.setMockInitialValues({}); ` in my code anywhere – CodeGeek Mar 29 '19 at 07:49
  • All I could suggest is to try the reference on https://pub.dartlang.org/packages/shared_preferences: `_incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = (prefs.getInt('counter') ?? 0) + 1; print('Pressed $counter times.'); await prefs.setInt('counter', counter); }` – jeangali Mar 29 '19 at 16:00
  • 1
    I have the same issue but this solution didn't work. @jérémy did you find a solution? – Leonardo Rignanese Jun 27 '19 at 11:14
  • Does this solution matter to ios? I have the same issue in ios. – Nero Dec 02 '20 at 11:02
1

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

Saranya Subramanian
  • 417
  • 1
  • 5
  • 19