123

My Flutter application uses the Flutter SharedPreferences plugin and send values to the iOS side with platform.invokeMethod. If I start the application, I have this error:

[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
#0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:278:7)
<asynchronous suspension>
#1      SharedPreferences.getInstance (package:shared_preferences/shared_preferences.dart:25:27)
<asynchronous suspension>
#2      main (file:///Users/Developer/workspace/flutter-app/q_flutter2/lib/main.dart:25:53)
<asynchronous suspension>
#3      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

If I comment the function to send the value to iOS side, the error is not displayed and the SharedPreferences is working.

Someone can help me?

camilleB
  • 1,961
  • 4
  • 15
  • 20
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/219496/discussion-on-question-by-camilleb-flutter-unhandled-exception-missingpluginex). – Martijn Pieters Aug 09 '20 at 14:13
  • I replaced shared_prefs to flutter_secure_storage – Roman Soviak Apr 21 '21 at 15:24
  • I'm facing this issue ONLY after deploying my app to playstore (run/build in both release and debug modes works fine). Any ideas why this could be happening? – Hugo Sartori Jun 21 '21 at 21:48

33 Answers33

112

No implementation found for method getAll on channel plugins.flutter.io.

The above will occur when you setup the plugin for the first time, so it has to be reinstalled.

Therefore, uninstall and reinstall your application.

double-beep
  • 5,031
  • 17
  • 33
  • 41
kriss
  • 1,421
  • 1
  • 8
  • 16
60

After doing a lot of research, I found the answer. Add this to your code before you use shared preferences.

SharedPreferences.setMockInitialValues({});

It is because if you use getAll where there is nothing, it will go crazy. I don't think it is anything to do with iOS. If you even use normal getString, the internal program uses getAll so it will still crash

EDIT

I have been receiving a lot of comments on how it does not persist data b/w sessions. What you can do to fix that is put it in a try and catch statement. In try, call sharedPreferences.get and catch the error and then do setMockInitialValues. If sharedPreferences.get does not give an error, it means there is already data and no need to set mock values replacing the old ones.

I am not sure if that will work so if anyone tries it and it helps in persisting data, let me know so that I can validate it for others

EDIT 2

Thanks to Edwin Nyawoli, I now know why it did not persist data in between sessions. While mine is a temporary and not a real solution, it still may help. If someone can help me recreate this issue on my new device, I can try to figure out a new solution. Please let me know if you are willing to upload your project to github so that I can recreate it. For now, I did some more research and believe this might help you:-

In /android/app/build.gradle

buildTypes {
    release {
        signingConfig signingConfigs.release

        minifyEnabled true
        useProguard true

        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

change to

buildTypes {
    release {
        signingConfig signingConfigs.release

        minifyEnabled true
        useProguard true

        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

This answer is not mine, its from this comment on a github issue https://github.com/flutter/flutter/issues/65334#issuecomment-760270219

Siddharth Agrawal
  • 2,960
  • 3
  • 16
  • 37
  • 4
    this way we got a warning saying this setMockInitialValues should only be called internally or in a test – FAjir Sep 18 '20 at 15:27
  • Yeah but it does not cause any problem. I have been using it for a long time and it is running perfectly – Siddharth Agrawal Sep 19 '20 at 07:11
  • It's really weird, I prefer not using this lib instead of adding weird workaround like that – FAjir Oct 31 '20 at 00:18
  • Shared Preferences is a very good library and its very useful but its upto you. – Siddharth Agrawal Nov 02 '20 at 07:05
  • With this line I get: Error: Getter not found: 'SharedPreferences'.SharedPreferences.setMockInitialValues({}); – Atul Jan 10 '21 at 07:39
  • Have you done stuff like flutter clean and all – Siddharth Agrawal Jan 14 '21 at 03:58
  • I would recommend to cautiously use this. For me It's not persisting data between sessions. – blisssan Jan 26 '21 at 20:06
  • as @Konstantin Kozirev pointed out, it's important to note that this should not be used in production apps – stevenspiel Feb 15 '21 at 14:27
  • I used this solution but shared preference remove all data after closing the app. – Mr. ZeroOne Mar 11 '21 at 05:14
  • You must have made a mistake at some other place since it sets mock initial values when your app is first installed. You can open a new issue with some code of how you are using this and I will be happy to help you out – Siddharth Agrawal Mar 11 '21 at 08:34
  • 2
    Exception gone, but it loose the value if app closed. giving null on restarting app. – Vishva Vijay Mar 22 '21 at 06:06
  • Maybe put the call of shared preferences in a try block and if it throws an error or is empty you can call this – Siddharth Agrawal Mar 22 '21 at 16:41
  • When you look at the internals of SharedPreferences, calling this method will switch to using an `InMemorySharedPreferencesStore` instead of the store that persists preferences to disk – Edwin Nyawoli Apr 22 '21 at 10:14
  • Oooh. So I guess my solution isn't really a solution. We need a permanent storage. Can anyone test out what happens once you use this, then remove it? I will try to recreate the issue and see what other things work in the mwantime – Siddharth Agrawal May 24 '21 at 15:50
  • @SiddharthAgrawal so is there any othersolution.. setMockInitialValues({}) is not persisting data for my app.. idk why everyone have this problem only on android while i have this in ios.. other developer in my team didn't have this error though.. – anas Mar 21 '23 at 09:15
38

SOLUTION

Step 1: Update buildTypes in /android/app/build.gradle


android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
       ...
    }

    signingConfigs {
        release {
            ...
        }
    }

    buildTypes {
        debug {
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }

        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            // signingConfig signingConfigs.debug

            signingConfig signingConfigs.release

            minifyEnabled false
            shrinkResources false

            useProguard true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Step 2: Add file android/app/proguard-rules.pro:

-keep class androidx.lifecycle.DefaultLifecycleObserver

Step 3: Update MainActivity


import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    GeneratedPluginRegistrant.registerWith(flutterEngine) // add this line
  }
}

  • 5
    In my case Step1 and Step 2 were enough – Kedar Sukerkar Mar 06 '21 at 13:23
  • 1
    I also need include `SharedPreferences.setMockInitialValues({});` in `main.dart` at root folder (module), then define `shared_preferences` in `pubspec.yaml` at root folder (module), to fix this issue. My case is include flutter module to native projects. – Huy Tower Aug 04 '21 at 02:48
  • 1
    Only step 1 is needed here. Great! Thanks a lot – thanhbinh84 Aug 26 '21 at 09:24
36

I had this issue before and this is what I have done to fix it:

  1. Run flutter clean
  2. Run flutter pub get

after that delete your debug app from the device.

Ahmad
  • 1,618
  • 5
  • 24
  • 46
Amjad Alwareh
  • 2,926
  • 22
  • 27
16

This gave me a nightmare as well.

  • minifyEnabled false
  • shrinkResources false

    Adding these two lines inside buildTypes in app/build.gradle worked for me.
android {
    //

    defaultConfig {
        ...
    }

    buildTypes {
        release {
            signingConfig signingConfigs.debug
            minifyEnabled false
            shrinkResources false
        }
    }
}

I've worked with shared_prefs before but got stuck in this one on my recent project. The community shall look into this.

Yuvraj Singh
  • 644
  • 6
  • 6
13

Got the same problem after adding Shared Preferences to my project and running it on an emulator. The following steps solved the problem for me:

  1. Run 'flutter clean'
  2. Run 'flutter pub get'
  3. Delete the app from the emulator
positrix
  • 154
  • 1
  • 5
13

On 14.02.2022 i had this problem with shared_preferences^2.0.8 when used it in background service. Adding these lines in pubspec.yaml fixed the problem:

dependency_overrides:
  shared_preferences_android: 2.0.10 
Viktar K
  • 1,409
  • 2
  • 16
  • 22
9

For android part, you should not use

SharedPreferences.setMockInitialValues({});

because it's not persisting your preference.

instead, add the following line to your app/proguard-rules.pro:

-keep class androidx.lifecycle.DefaultLifecycleObserver

see https://github.com/flutter/flutter/issues/58479#issuecomment-734099445

See related issue: https://github.com/flutter/flutter/issues/65334

ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • This did help me, but I had to follow this comment to use "proguard-android-optimize.txt" https://github.com/flutter/flutter/issues/65334#issuecomment-760270219 – blisssan Mar 07 '21 at 13:42
  • SharedPreferences.setMockInitialValues({}); \n adding this line above runApp(MyApp()); worked for me – Apoorv Pandey Jul 23 '21 at 05:51
9

Faced this issue and fixed by completely reinstalling the app

ikhsanudinhakim
  • 1,554
  • 16
  • 23
8

So after creating flutter a dummy project to test the solution here to the 'T', which didn't work for me. I finally resolved it by updating the MainActivity.kt file.

My solution was simply to add the line flutterEngine.getPlugins().add(SharedPreferencesPlugin())

Here is the Full MainActivity.kt file :

package com.example.begin.init_begin
import android.content.Context
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin

class MainActivity: FlutterActivity() {

override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    flutterEngine.getPlugins().add(SharedPreferencesPlugin())

}

}

Please note: The GeneratePluginRegistrant.java already has the registration but in my case adding it as shown above is what resolves the issue.

DainShardz
  • 81
  • 1
  • 2
6

In my case, I removed the package "flutter_facebook_login: ^3.0.0" in pubspec.yaml file, and then it is working well...

I have tried all the above solutions, but there is not any other better solution than removing the "flutter_facebook_login" package.

In some above solutions MissingPluginException could be fixed, but get() and set() of shared_preferences are not working properly.

Please let me know about a better solution.

persec10000
  • 820
  • 2
  • 10
  • 17
  • 3
    I have solved my problem by setting up Facebook auth on Android first before running the app. You can't run the app without doing the whole Android facebook setup. – Alvindrakes Jun 08 '21 at 17:28
  • This is what solved the issue for me as well. If you're using the "flutter_facebook_login" package, set it up completely by following the steps given in the website for the package. – Parampreet Dhatt Aug 19 '21 at 07:56
6

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

then add this to your in main() function of main.dart file

main(){

SharedPreferences.setMockInitialValues({});

... ...

}

**this worked for me ! **

ONeils'
  • 61
  • 1
  • 4
6

I've encountered the same issue while using background_fetch when the app is terminated and the headless task was executed with a callback that wanted to access shared_preferences package.

import 'package:shared_preferences_ios/shared_preferences_ios.dart';
import 'package:shared_preferences_android/shared_preferences_android.dart';
import 'dart:io';

///Other code

//Add the check and registerWtih in your desired method.
if (Platform.isAndroid) {
  SharedPreferencesAndroid.registerWith();
} else if (Platform.isIOS) {
  SharedPreferencesIOS.registerWith();
}

Code using background_fetch:

import 'package:shared_preferences_android/shared_preferences_android.dart';
import 'dart:io';

///Other code

void backgroundFetchHeadlessTask(HeadlessTask task) async {
  SharedPreferencesAndroid.registerWith();
  //No need to check OS because headless task works only for Android

///code code
}
Philipos D.
  • 2,036
  • 1
  • 26
  • 33
4

Check AppDelegate. Channel registration should be after plugins registration

...
@objc class AppDelegate: FlutterAppDelegate {

    override func application(
    ...
        GeneratedPluginRegistrant.register(with: self)
        channel = FlutterMethodChannel.init(name: "dressme.lofesdev.com/geo",
                                        binaryMessenger: controller);
    ...
Dmitry
  • 141
  • 1
  • 8
  • 1
    Hi @Dmitry can you please help with object-c version with firebase config? Currently I use follow import UIKit; import Firebase; implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; return YES; } but I have same error like OP – Ilya Sulimanov Jan 01 '20 at 17:22
  • 1
    this answer is irrelevant because it only affects the ios build, android being also affected it is not viable – FAjir Sep 18 '20 at 15:26
4

I have tried all the above-suggested solutions when working with Workmanager for background fetch, nothing solved the problem. :(

Finally, I did as below, the issue is resolved.

In main.dart:

if (Platform.isAndroid) {
        SharedPreferencesAndroid.registerWith();
      } else if (Platform.isIOS) {
        SharedPreferencesIOS.registerWith();
      }

In pubspec.yaml:

shared_preferences_ios:
shared_preferences_android:
Achilles
  • 41
  • 2
2

I also had this error using in Debugging mode using VS Code. I just stop, then start again the app (without to directly restart).

Run > Stop Debugging

Run > Start Debugging

Adrien Arcuri
  • 1,962
  • 1
  • 16
  • 30
2

In my solution, I haven't used SharedPreferences.setMockInitialValues({}); as other folks fairly said that it shall be used for test (and IDE also says so), but not for production app. So I noticed that Flutter says that my project uses old flutter android embedded version and I should upgrade to v2. And I did so, using this instruction: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects

After that the error about MissingPluginException disappeared. So it seems a bit better solution, than calling method for test. I wish I could know why, but at this moment I just don't have time to dig too much inside. Anyway, this is another solution to this issue.

Konstantin Kozirev
  • 944
  • 1
  • 10
  • 23
2

If you are facing this error on Flutter Web, using Chrome for debug here is what a I did:

In my case, I had to simply completely close the Chrome window Flutter was using.

Runned the app again, the error was gone and the shared_preferences worked fine!

Hope it helps!

Geraldo Neto
  • 3,670
  • 1
  • 30
  • 33
1

In my case, reinstalling the application didn't work.

Instead, go to the AppDelegate.m file, path ios/runner/AppDelegate.m:

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"

@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [FIRApp configure];
    [GeneratedPluginRegistrant registerWithRegistry:self];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}


@end

Then delete your application from the device then run the application again.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Abel Tilahun
  • 1,705
  • 1
  • 16
  • 25
1

Maybe this will help if the above answers won't work. While creating the android studio flutter project i forgot to check the boxes for including kotlin support for android / swift support for iOS. It was so because after flutter clean and flutter run my project didn't work.

Omi
  • 61
  • 1
  • 7
1

Just use

classpath 'com.android.tools.build:gradle:3.5.1'

inside your android/build.gradle

M.AQIB
  • 359
  • 5
  • 11
1

Run flutter clean and after that Run flutter pub get

Usually if you implemented the shared preferences package during your debugging, it may causes this issue, so try to stop the debug the method above and it should work.

Hassan Serhan
  • 392
  • 3
  • 13
1

In my case, I solved this by adding bellow line in /android/app/build.gradle

buildTypes {
    release {
        signingConfig signingConfigs.release
    }
}

To

buildTypes {
        release {
            signingConfig signingConfigs.release
            
            minifyEnabled true
            useProguard true

            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
}
0

I was receiving this issue with one of the flutter packages and upgrading the package to the latest version helped.

ram
  • 9
  • 1
0

I got this issue in Flutter Web. I added the code, used "fast restart" and got this error. Stopping and restarting solved the problem for me.

AzureIP
  • 338
  • 1
  • 10
0

I had the same issue a couple of days ago, after days of googling I found out that the reason shared preferences is not working, is that I had a package that had not been properly configured "flutter_facebook_login". Thus any package after Facebook, will not work, in this case, "shared preferences".

Solution: Make sure every package you are using has been fully configured or remove the package that is causing the problem.

Luis Alt
  • 21
  • 2
0

Tried everything I could find, none of it worked. Was reluctant when I saw comment with -2 suggesting flutter_fackbook_login package was causing the issue. Later again found here about flutter_fackbook_login being the issue. After removing the package it worked!

zorro
  • 101
  • 1
  • 10
0

This main.dart add line

SharedPreferences.setMockInitialValues({});

I am solved

  • 1
    use of this is not appreciated in main.dart. You can populate SharedPreferences with initial values in your tests by running this code. just reinstall the app . that should solve the issue. – Md. Hasan Mahmud Aug 15 '21 at 12:47
0

In my case, it was just increasing the minSdkVersion. I found this when I started my app from cold (not by clicking the restart button). -

The plugin flutter_webrtc requires a higher Android SDK version.
Fix this issue by adding the following to the file C:\Users\Piyush\Documents\filesfi\android\app\build.gradle:
android {
  defaultConfig {
    minSdkVersion 21
  }
}
Piyush
  • 693
  • 1
  • 7
  • 12
0

As in my case, I have a flutter MODULE embedded in an iOS application. The MissingPluginException issues are raised due to incorrect registration of plugins.

The following code example works:

import Flutter
import FlutterPluginRegistrant

@main 
class AppDelegate: FlutterAppDelegate {

    ...

    var flutterEngine: FlutterEngine!

    ...

    func application(
        _ application: UIApplication, 
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool 
    {
        // Override point for customization after application launch.
        self.flutterEngine = FlutterEngine(name: "my flutter engine")
        self.flutterEngine.run()
        // register plugins onto engine, NOT AppDelegate itself;
        GeneratedPluginRegistrant.register(with: self.flutterEngine)
        return true
    }

    ...

}
Ke Yang
  • 881
  • 1
  • 12
  • 21
0

You can solve this error by using try. Here is an example:

_checkLoginStatus() async {
try {
  SharedPreferences localStorage = await SharedPreferences.getInstance();
  var token = localStorage.getString('token');
  if (token != null) {
    setState(() {
      _isLoggedIn = true;
    });
  }
} catch (e) {
  //
}

}

0

In my case i just removed the "admob_flutter" login package. And everything works fine.

Xavier Soh
  • 47
  • 5
-1

AndroidManifest.xml

    <activity
        android:name="io.flutter.embedding.android.FlutterActivity">
    </activity>
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />

Mark these 2 code properly as I was changing the flutter embedding to v2 it occurred so I properly checked these 2 code and it removed my error.

Spsnamta
  • 479
  • 6
  • 11