clear shared preferences from myBackgroundMessageHandler - flutter

I want to clear shared preferences when I send a FCM message and app is in background. Inside myBackgroundMessageHandler method I am calling a method to clear them.
static Future<dynamic> myBackgroundMessageHandler(
Map<String, dynamic> message) {
clearPreferences();
}
static void clearPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();
}
I am getting the following error:
Unhandled Exception: MissingPluginException(No implementation found
for method getAll on channel plugins.flutter.io/shared_preferences)

step 1)
go to Application.kt/Application.java (in my case is kotlin)
step 2)
add these line into Application class (in kotlin)
if (!registry!!.hasPlugin("io.flutter.plugins.sharedpreferences")) {
SharedPreferencesPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin"));
}
remember import this as well
import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin
step 3)
run flutter clean -> flutter get -> uninstall your app

The code is completely fine.
Just restart your emulator. If you didn't do a full restart by closing the emulator and open it up again, this error can propably occur, because it doesnt have the newly added plugins.

Add SharedPreferences.setMockInitialValues({}) to your code before the runApp() function inside the main function of Flutter App.
this fixed the error for me

Related

Flutter: How to get/write data from/to shared preferences from action button's click using Awesome notifications?

I am using Awesome notifications to display notifications in my app. In the notifications, I have an action button, and when pressing it, the app is supposed to read and write some simple data from/to the memory of the phone using shared preferences. This is supposed to happen in the background without opening the app in the foreground.
I tried the following code:
#pragma("vm:entry-point")
static Future<void> onActionReceivedMethod(ReceivedAction action) async {
print('It works');
print(action.toMap());
final SharedPreferences prefs = await SharedPreferences.getInstance();
List<PinnedFolder> pinnedList = [];
try {
final String? pinnedString = prefs.getString('pinnedKey');
if (pinnedString != null) {
pinnedList = PinnedFolder.decode(pinnedString);
print('PinnedList got from memory, length: ${pinnedList.first.pinnedList.length}');
}
} catch (error) {
debugPrint('Error: couldnt get pinned folders: $error');
}
The "It works" and 'action.toMap()' get printed, but I can't get data from shared preferences. Is it so, that I can't use added packages in #pragma("vm:entry-point") functions? What would be the best way to fix the code? The action doesn't need to happen right after the button press, it can also happen the next time when the app is in the foreground, but so that the button action information is still available.
I found a solution using the package flutter_secure_storage.
const storage = FlutterSecureStorage(); await storage.write(key: my_key, value: my_value);
It seems to be so that only a few packages work in #pragma("vm:entry-point") functions, but this is one of them. I implemented it so that every time the app opens, it gets and handles the data from the secure storage before the app is launched.

Open a screen when firebase notification received in flutter while app is background or terminated

want to create a screen that launch when a firebase notification is received while the app is in the background or terminated in flutter (like package callKeep ).please anyone help me create that.
You just need to handle its background handler method it will works.You need to initialize this method in main() method.
Future<void> backgroundHandler(RemoteMessage message) async {
debugPrint(message.toString());
debugPrint(message.data.toString());
debugPrint(message.notification!.title);
}
FirebaseMessaging.onBackgroundMessage(backgroundHandler);

Flutter url_launcher not working MissingPluginException

i want to launch google map when tap on button, nothing complicated. i found easy code also from google search. Pasting the code below for reference. i dont know it is the proper way to do.
class MapUtils {
MapUtils._();
static Future<void> openMap(double latitude, double longitude) async {
String googleUrl =
'https://www.google.com/maps/search/?api=1&query=$latitude,$longitude';
if (await canLaunch(googleUrl)) {
await launch(googleUrl);
} else {
throw 'Could not open the map.';
}
}
}
pubspec.yaml added -> url_launcher: ^6.0.17
i called this -> MapUtils.openMap(-33.2445107, 9.1530103)
Whenever i tap on the button return error as "Unhandled Exception: MissingPluginException(No implementation found for method launch on channel plugins.flutter.io/url_launcher)"
i tried to find solution, what i tried is
Flutter clean, flutter pub get.
Close everything reopen
uninstall app from emulator device.
close emulator and restart.
total computer restart.
it is nothing related url_launcher still i add the google map api to androidmanifest and appdelegate. Enables Api.
Lot of popel are asking about the same error. May be i am missing something todo.

Error When Forcing Portrait Orientation in Flutter

I am trying to force my Flutter app to only use Portrait mode. My main() method looks like this.
void main() {
SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS)
.then((_) => runApp(MyApp()));
}
Here is the definition of ALLOWED_ORIENTATIONS:
const List<DeviceOrientation> ALLOWED_ORIENTATIONS = [
DeviceOrientation.portraitUp
];
I just separated all the settings and such to another file to make modifying them later on easier.
When I run this code, I get the following error.
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
If you're running an application and need to access the binary messenger before `runApp()`
has been called (for example, during plugin initialization), then you need to explicitly
call the `WidgetsFlutterBinding.ensureInitialized()` first.
It looks like there is some race condition that's failing. I am just not sure what is causing it. Removing the SystemChrome.setPreferredOrientations() line makes the app compile as expected. So, I am thinking the error has something to do with that line.
Any advice?
Like the error says
If you're running an application and need to access the binary
messenger before runApp() has been called (for example, during
plugin initialization), then you need to explicitly call the
WidgetsFlutterBinding.ensureInitialized() first.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(uiOverlayStyle);
await SystemChrome.setPreferredOrientations(ALLOWED_ORIENTATIONS);
runApp(MyApp());
}

Flutter using plugins inside flutter workmanager plugin callbackDispatcher function

I try to use sqflite plugin inside background process with flutter workmanager. I have an SQLHelper class which for sqflite operations. I can use this helper inside application. But in this background process, it gives error as below
Exception has occurred:
MissingPluginException (MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite))
Probably I have to register plugin inside callbackDispatcher, but I'm not sure. How can I solve this problem?
void callbackDispatcher() {
Workmanager.executeTask((task, inputData) async {
SQLHelper db = SQLHelper();
ServerSetting sItem = await db.settingGetItem();
print(sItem.hidetriggermaintenance);
return Future.value(true);
});
}
you need to register sqflite plugin on native side, as stated here: https://github.com/tekartik/sqflite/blob/master/sqflite/doc/troubleshooting.md