SharedPreferences works with iOS, with Android it doesn't

Hi everybody,

I want to simply use SharedPrefences both in iOS and Android.
iOS does work perfectly but in Android it doesn’t.

In iOS I have set up the necessary permission in info.plist. On Android side I don’t know if there are any permission I have to set up. Any advice?

Currently on iOS I got the expected results: values going to store and display as I want. In Android nothing happened.

For example my code for storing and reading an inserted username:
void saveName() async {
var prefs = await SharedPreferences.getInstance();
var key = ‘name’;
await prefs.setString(key, username);
}

Future readName() async {
var prefs = await SharedPreferences.getInstance();
var key = ‘name’;
username = prefs.getString(key);
return username;
}

Have anybody an advice or experience with permissions in Android or know something about that issue?

Thanks in advance!

Hi, I’ve implemented multiple times that plugin and didn’t need any setup, not even for iOS, and worked well on both platform. Could you share the link to the package you are using?

Do you here any errors on Android?

1 Like

I have using the following package: https://pub.dev/packages/shared_preferences
I got no errors on Android.

I am using the readName() method at the start up process of my app. Either the app has a name stored or asking about a name. Currently I only get a loading screen what means that the app get not data.

Hey @n1c0_1202 I have this setting for another plugin, but that may be the cause it works for me out of the box on Android. Let me know if it works and I’ll add a request on the package to add it to the ReadMe.

In your AndroidManifest.xml in android>app>src>main in the application tag add this:
android:requestLegacyExternalStorage="true".

I would agree with @F.lucadetena, it works smoothly for Android, have used it in multiple production level Applications. What exactly do you mean by nothing happened? I would suggest you put a print right before the await prefs.setString(key, username); and check the value of username. It is possible that this value is not coming correctly. Also you don’t need to assign ‘name’ to a variable, you can simply right
prefs.setString('name', username); .

I can tell from personal experience that there is no Android specific issue with this plugin.

1 Like

With the added settings in AndroidManifest it still doesn’t work.

@sakina I have the readName() as a startup future in my code. Either it has a name or it has not but currently the return value is null. Neither true nor false.
I tried with a print and without the assigned variable ‘name’ but no success.

Important note: in debug mode (in emulator) it works for Android, but it doesn’t in release mode on a physical device. Is there any permission dialog under android I have to call?

This is my startup future method:
Future readStartData() async {
var prefs = await SharedPreferences.getInstance();
var keyName = ‘name’;
var keyHome = ‘home’;
username = prefs.getString(keyName);
homeLocation = prefs.getString(keyHome);
return username == null && homeLocation == null;
}

And this is the FutureBuilder with the method inside:
FutureBuilder(
future: readStartData(),
builder: (buildContext, snapshot) {
if (snapshot.hasData) {
print(snapshot.hasData);
if (snapshot.data) {
print(snapshot.data);
return SliderWidget();
}

That is super strange. You should not need to call any permission for that in IOS or Android. Have you try, completely erasing the app and reinstalling??

When you say you call the Future at startup, what do you mean? Are you calling the

before

runApp(MyApp());

or after?

Yes, I tried it multiple times. Therefore I thought I have forgot some permissions.

The app calls the main.dart at the beginning. Than I have assigned a welcome widget and inside of the welcome widget it will call the readStartData() method.
To answer your question: after runApp(MaterialApp());
Below the code snippet of my main.dart:

void main() {
runApp(MaterialApp(
title: ‘Good Farmer’,
debugShowCheckedModeBanner: false,
home: WelcomeScreen(),
theme: ThemeData(primaryColor: Colors.white),
))}

It is very strange. Have you tried on a blank new project? Maybe it is some package conflicting with this one.

Is this an API call?

Maybe you have forgotten to add the internet permission in Android Manifest. This is just a guess, because I can’t seem to find any issue with the shared preferences in release mode.

@sakina the internet permission is set in android>app>src>main>AndroidManifest.xml:

Btw: my package version of shared_preferences is ^0.5.8
I will update to ^0.5.12 (current version).

I found this helpful code snippet in https://github.com/flutter/flutter/issues/41119

Try to have such MainActivity.kt

package com.example.bug

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

What do you think about that? It seems that it helps some other users.

Maybe it helps you. I would first try to update everything. Flutter and all the packages. That may resolve some conflicts.

I try to modify as less native as a I can, as that may affect future updates. And one of the great things of flutter is the easiness to keep everything to date.

Btw, have you tried with a clean new project?

Yes, I tried a new blank project but without success.
I checked the FutureBuilder with printouts if the values will be called correctly and it does.

I will update the version and try it again.

Ok let me know what happens :wink:

Long time no see :slightly_smiling_face:
Sorry for that.

I have updated all dependencies and tested again but no success.
After that I have changed the key value store from shared_preferences to the hive store but all of that have changed nothing.

So I think it doesn’t depend on the plugin.

Maybe you need to try to erase and reinstall flutter?? Have know idea where you can go. It should work out of the box flawlessly

@F.lucadetena Erase and reinstall flutter? How can I do this?

Delete the flutter sdk, it should be a folder somewhere. Check the path in your bash file.

And follow steps for installation on flutter.dev

Ok thanks for your help.
I have deleted the folder und downloaded the latest stable version 1.22.2.
Works fine with iOS, Android doesn’t …

In several article (e.g. https://www.developerlibs.com/2018/07/flutter-how-to-fix-white-screen-on-app.html) I read about a white screen if you have unchanged the launch_background.xml in android > app > src > main > res > drawable

Did you hear already about that problem?

No, I am afraid I haven’t heard about this issue. Could you share the error log when you are trying to run for android. Also please share the flutter doctor output as well