FlutterFire Messaging : MissingPluginException error thrown for Shared Preferences - flutter

I'm using firebase and shared_preference in my flutter project, where I need to store a incoming message to the shared preferences. Whenever a message is received, I am getting the below exception
I/flutter (29300): FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter (29300): MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
I know that _firebaseMessagingBackgroundHandler will spawn a new isolate, but does that make other plugins unaccessible??
This is my handler
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
await prefs.setStringList(
DateTime.now().toIso8601String().substring(0, 19) + ".000000", [message.notification!.body.toString(), message.notification!.title.toString()]);
}
I have also confirmed that shared preferences present in generated_plugin_registrant.dart. I have used FlutterFire CLI for integerating firebase with my app.

Related

Flutter Crashlytics SocketException: Reading from a closed socket

While examining the Firebase crash logs one of our application in production mode, we found the following exception:
Non-fatal Exception: io.flutter.plugins.firebase.crashlytics.FlutterError: SocketException: Reading from a closed socket. Error thrown null.
at _RawReceivePortImpl._handleMessage(_RawReceivePortImpl.java)
That's it, nothing more. How can I set up a more detailed log in Firebase Crashlytics? What could throw such an error? We use websocket, Drift, Dio.
Firebase Crashlytics setup:
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
runZonedGuarded(
() => runApp(const MonitorMobileApp()),
(error, stackTrace) {
FirebaseCrashlytics.instance.recordError(error, stackTrace);
},
);
Thank you in advance.

Unhandled Exception when initializing firebase on windows

Hi guys first time here on stack overflow.
I am currently building an app using flutter with firebase as the backend.
My target platforms are Windows and android
The android app builds fine
The windows app throws :
ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception:
PlatformException(channel-error, Unable to establish connection on
channel., null, null)
this only happens when I use :
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
I have also tried :
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "myapi",
appId: "appid",
messagingSenderId: "senderid",
projectId: "projectid",
storageBucket: "buckedid",
databaseURL: 'databaseurl',
));
As stated this works fine on android but not windows
I have the latest dependencies for Firebase
I have tried flutter pub outdated and it returns no Firebase dependencies
I have tried flutter pub upgrade
I have tried flutter clear
Hey if you are using the the latest versions of firebase you'd want to follow through the newest way of initializing firebase with firebase CLI. See this https://firebase.flutter.dev/docs/cli starting off by activating firebase cli
have something like this
// Import the generated file
import 'firebase_options.dart'; //this provides the current platform options via the currentPlatform getter from the DefaultFirebaseOptions class
...
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "API KEY",//<<==
appId: "ID",//<<==
messagingSenderId: "IF ANY",//<<==
projectId: "Project ID",//<<==
),
...

core/no-app No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

When I try to launch my Flutter Web App with Firebase I get the following error in my terminal
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following FirebaseException was thrown building HomePage(dirty, dependencies: [MediaQuery]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
HomePage HomePage:file:///C:/Flutter/pbwebapp/lib/main.dart:37:13
When the exception was thrown, this was the stack:
...
I found other people had problems with this error but in my case I have called Firebase.initializeApp() in my main.dart file and I have also imported firebase_core in my pubspec.yaml
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
name: "pbwebapp",
options: const FirebaseOptions(
apiKey: "...",
authDomain: "..",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "...",
),
);
runApp(MyApp());
}
Does anyone had this problem with Firebase trying to launch a Flutter Web App?
Thanks in advance!
Use Flutter Fire Cli to add flutter firebase packages like auth, messaging etc,
It will automatically configure all the things for you.
https://firebase.google.com/docs/flutter/setup?platform=ios
Okay so somehow removing the name parameter in the Firebase.initializeApp() function worked for me. But I dont know why exactly

Error getting App Check token; using placeholder token instead

My app was working normally since today.I already included Firebase Storage in my Android Flutter App and it works after that today I get AppCheck Errors suddenly. I was not include App Check for our project or not enforced in settings. After that I was following the official documentation for initialization appcheck : https://firebase.flutter.dev/docs/app-check/usage.
This is my Kotlin MainActivity:
import android.os.Bundle
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(/*context=*/ this);
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance())
super.onCreate(savedInstanceState)
}
}
and this is my main():
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAppCheck.instance.activate();
runApp(MyApp());
}
I also added this to my app/build.gradle
dependencies {
implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta01'
}
When I make a request to firebase storage, I would expect something like this in my console:
D DebugAppCheckProvider: Enter this debug secret into the allow list in the Firebase Console for your project: 123a4567-b89c-12d3-e456-789012345678
Instead, I'm getting an error:
2021-11-21 18:11:51.442 2091-3452/com.sekspir.grind4gain W/ExponenentialBackoff: network unavailable, sleeping.
2021-11-21 18:11:53.500 2091-3452/com.sekspir.grind4gain W/StorageUtil: Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Error returned from API. code: 403 body: App attestation failed.
2021-11-21 18:12:11.136 2091-3633/com.sekspir.grind4gain V/NativeCrypto: SSL handshake aborted: ssl=0xdaa42da8: I/O error during system call, Connection reset by peer
Did I miss something here? I am using a real Android device with flutter debug build.
This is Firestore AppCheck Stats looks both of request income
But in Storage session there are not any request fail or success.
Can you double check that you correctly enabled the enforcement ?
It is required to work with Firebase Storage solutions.
Are you using your app in "PWA" mode or in "Native" mode ?
The Recaptcha may be mandatory depending on how your app is distributed.
await FirebaseAppCheck.instance.activate(
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
);
I'm not sure about your implementation of the appcheck-debug dependency on the Android Native side.
Since it's already implemented by the Flutter library itself, you should remove it.
Personal note : I had troubles with FirebaseAppCheck on some devices, while it was working perfectly on other devices.
This library is still in beta and I would recommend to wait before using it in production.

Flutter Driver hangs at splash screen

I am trying to setup Flutter Driver tests for my application and the app runs async so I found https://github.com/flutter/flutter/issues/41029 which says all you need to do is add await driver.waitUntilFirstFrameRasterized(); and it should work, while this does stop the test from failing it nos simply does not run.
The app just hangs at the splash screen never even getting into the application itself.
As far as I am understanding, this is all I would need to have setup in order for the test to run
FlutterDriver driver;
// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
await driver.waitUntilFirstFrameRasterized();
// await Directory('screenshots').create();
});
// Close the connection to the driver after the tests have completed.
tearDownAll(() async {
if (driver != null) {
await driver.close();
}
});
However, all I am getting in my terminal is the following output:
VMServiceFlutterDriver: Connecting to Flutter application at http://127.0.0.1:54264/tt9kN4jBSrc=/
VMServiceFlutterDriver: Isolate found with number: 2942164624858163
VMServiceFlutterDriver: Isolate is paused at start.
VMServiceFlutterDriver: Attempting to resume isolate
VMServiceFlutterDriver: Connected to Flutter application.
VMServiceFlutterDriver: waitForCondition message is taking a long time to complete...
I have left it for minutes and nothing happens, I have disabled the firebase initialization in case somehow that is blocking it as I would need to accept the alert dialogue, not that I am even getting that far as I can see.
Turns out I needed to use an IsolatesWorkaround as well
FlutterDriver driver;
IsolatesWorkaround workaround;
// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
workaround = IsolatesWorkaround(driver);
await workaround.resumeIsolates();
await driver.waitUntilFirstFrameRasterized();
if (!await Directory('screenshots').exists()) {
await Directory('screenshots').create();
}
});
// Close the connection to the driver after the tests have completed.
tearDownAll(() async {
await driver?.close();
await workaround.tearDown();
});
See: https://gist.github.com/vishna/03c5d5e8eb14c5e567256782cddce8b4