Google SignIn Flutter Error: Assertion Failed - flutter

I am creating a fLutter app and I am trying to login using Firebase google_sign_in. But I am getting some error: Assertion Failed
That's my function:
void signInWithGoogle() async {
final GoogleSignIn _googleSignIn = GoogleSignIn();
try {
GoogleSignInAccount? account = await _googleSignIn.signIn();
if (account != null) {
final GoogleSignInAuthentication _authAccount =
await account.authentication;
final AuthCredential _credential = GoogleAuthProvider.credential(
idToken: _authAccount.idToken,
accessToken: _authAccount.accessToken,
);
UserCredential userCredential =
await _auth.signInWithCredential(_credential);
userCredential.user;
await saveUser(account);
}
} on Exception catch (error) {
AppLogger.e(error);
}
}
saveUser(GoogleSignInAccount account) {
userRf.doc(account.email).set({
"email": account.email,
"name": account.displayName,
"profilepic": account.photoUrl,
});
}
Error: Assertion failed:
..\…\lib\google_sign_in_web.dart:89
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 29:3 assertFailed
packages/google_sign_in_web/google_sign_in_web.dart 89:20 initWithParams
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54 runBody
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 123:5 _async
packages/google_sign_in_web/google_sign_in_web.dart 86:30 initWithParams
packages/google_sign_in/google_sign_in.dart 290:39 [_ensureInitialized]
packages/google_sign_in/google_sign_in.dart 271:11 _callMethod
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 84:54 runBody _addMethodCall <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 594:14 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 288:16 loggedHandler
C:/b/s/w/ir/cache/builder/src/out/host_debug/flutter_web_sdk/lib/_engine/engine/pointer_binding.dart 179:80 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14 _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39 dcall
I am new to Flutter. Please help me out.

Related

FLUTTER Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)

I got this problem when I use NoSQL Hive and in the pubspec.yaml file I set upped the path_provider package.
I ran the flutter pub get and tried to reinstall all packages and flutter clean but it's still got this error.
Error: MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw_
packages/flutter/src/services/platform_channel.dart 313:7 _invokeMethod
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50 <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1660:54 runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18 handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 767:44 handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 796:13 _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 567:5 [_completeWithValue]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 640:7 callback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 <fn>
This is my main file:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);
runApp(
DevicePreview(
enabled: !kReleaseMode,
builder: (context) => MyApp(), // Wrap your app
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
useInheritedMediaQuery: true,
locale: DevicePreview.locale(context),
builder: DevicePreview.appBuilder,
home: HomeScreen(),
);
}
}

Firebase verifyPhoneNumber with flutter is is giving me an error. I cannoty verify

I am working for an authentication with phone number in flutter. I am encountering an error with this.
Here is my code:
Future sendOTP() async {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) async {
print("VERIFICATION completed");
},
verificationFailed: (FirebaseAuthException e) {
print('VERIFICATION ERROR');
},
codeSent: (String verificationId, int? resendToken) async {
print('CODE SENT');
verID = verificationId;
token = resendToken;
},
codeAutoRetrievalTimeout: (String verificationId) {
//print("VERIFICATION timeout");
},
);
}
After sending the OTP to the phone number, and after the user triggers the send button, this method will fire;
void HandleOTP() async {
final _firebaseAuth = FirebaseAuth.instance;
final AuthCredential authCredential = await PhoneAuthProvider.credential(
smsCode: smsCode,
verificationId: verID,
);
print(authCredential);
await _firebaseAuth.signInWithCredential(authCredential);
}
and here is the problem that is printing in the console
I/flutter ( 5939): AuthCredential(providerId: phone, signInMethod: phone, token: null)
E/flutter ( 5939): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_auth/invalid-verification-id] The verification ID used to create the phone auth credential is invalid.
E/flutter ( 5939): #0 MethodChannelFirebaseAuth.signInWithCredential (package:firebase_auth_platform_interface/src/method_channel/method_channel_firebase_auth.dart:445:7)
E/flutter ( 5939): <asynchronous suspension>
E/flutter ( 5939): #1 FirebaseAuth.signInWithCredential (package:firebase_auth/src/firebase_auth.dart:497:7)
E/flutter ( 5939): <asynchronous suspension>
E/flutter ( 5939): #2 _OTPState.authenticate (package:rice_on_the_go/authentication/OTP.dart:215:5)
E/flutter ( 5939): <asynchronous suspension>
As you see, the value of the credential token is NULL, and why is that null? I hope someone help me to answer this.
Second, why is my verification ID is invalid? I checked it and it is not null.
Please help me solving this because I have been working for this for more than a day now. Thank you so much.
I make a common function for Firebase PhoneAuth you can try this:
Future<void> callPhoneAuth({required String phoneNumber, required void
Function(String, int?) codeSent, int? forceResendingToken}) async {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
verificationCompleted: (PhoneAuthCredential credential) {
FirebaseAuth.instance.signInWithCredential(credential);
kPrint('phoneauth is an -------- verifynumber ${credential}');
},
codeSent: codeSent,
timeout: const Duration(seconds: 60),
codeAutoRetrievalTimeout: (String verificationId) {},
forceResendingToken: forceResendingToken,
verificationFailed: (FirebaseAuthException e) {
if (e.code == 'invalid-phone-number') {
kPrint('phoneauth is an ---- The provided phone number is not valid.');
}
});
}
Use like this:
callPhoneAuth(
phoneNumber: '+1123456789', //Here your phone number with country dial code
codeSent: (String verificationId, int? resendToken) {
//This function called when your Otp successfully set it to phone number
});

Error: Member not found: 'FlutterLocalNotificationsPlugin.initialize'

I am trying to implement notifications on flutter but I am getting a weird error:
I am calling the following function:
initInfo() {
var androidInitialize =
const AndroidInitializationSettings("#mipmap/ic_launcher");
var iOSInitialize = const IOSInitializationSettings();
var initializationsSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
FlutterLocalNotificationsPlugin.initialize(initializationsSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) ;
} catch (e) {
print(e);
}
return;
});
}
I am getting the following error:
Instance member 'initialize' can't be accessed using static access.
here is the error log:
: Error: Member not found: 'FlutterLocalNotificationsPlugin.initialize'.
lib/navigator_view.dart:81
FlutterLocalNotificationsPlugin.initialize(initializationsSettings,
^^^^^^^^^^
Restarted application in 271ms.
I am trying to follow this video: https://youtu.be/AUU6gbDni4Q?t=845
I was able to get pass the initial error by doing this::
initInfo() {
var androidInitialize =
const AndroidInitializationSettings("#mipmap/ic_launcher");
var iOSInitialize = const IOSInitializationSettings();
var initializationsSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
var fln = FlutterLocalNotificationsPlugin(); // new code
fln.initialize(initializationsSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) ;
} catch (e) {
print(e);
}
return;
});
}
but now I am getting the following error:
/flutter (23250): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel dexterous.com/flutter/local_notifications)
E/flutter (23250): #0 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:294
E/flutter (23250): <asynchronous suspension>
E/flutter (23250): #1 AndroidFlutterLocalNotificationsPlugin.initialize
package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:85
E/flutter (23250): <asynchronous suspension>
E/flutter (23250):
should I not be doing this change?

Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type

I am trying to write a dart code program which can register users and sign in users, upon error print its description which i will eventually use in a Toast but it given an error on catchError
Future<void> signIn(String email, String password) async {
if (_form.currentState!.validate()) {
print(email);
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((uid) => {
Fluttertoast.showToast(msg: "Login Successfully"),
Navigator.of(context)
.pushReplacementNamed(UploadScreen.routeName),
})
.catchError((e) {
Fluttertoast.showToast(msg: 'Incorrect Email or Password.',
toastLength: Toast.LENGTH_LONG
);
});
}
}
E/flutter ( 7093): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type
E/flutter ( 7093): #0 _FutureListener.handleError (dart:async/future_impl.dart:193:7)
E/flutter ( 7093): #1 Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47)
E/flutter ( 7093): #2 Future._propagateToListeners (dart:async/future_impl.dart:799:13)
E/flutter ( 7093): #3 Future._completeError (dart:async/future_impl.dart:609:5)
E/flutter ( 7093): #4 _completeOnAsyncError (dart:async-patch/async_patch.dart:272:13)
E/flutter ( 7093): #5 FirebaseAuth.signInWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart)
E/flutter ( 7093):
E/flutter ( 7093):
Consider using try catch instead.
Try this:
Future<void> signIn(String email, String password) async {
try{
final User user = (await _auth.signInWithEmailAndPassword(
email: email,
password: password,
)).user;
Fluttertoast.showToast(msg: "Login Successfully"),
Navigator.of(context)
.pushReplacementNamed(UploadScreen.routeName),
} catch (e) {
Fluttertoast.showToast(msg: 'Incorrect Email or Password.',
toastLength: Toast.LENGTH_LONG
);
}
}
You can use onError function
Future<void> signIn(String email, String password) async {
if (_form.currentState!.validate()) {
print(email);
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((uid) => {
Fluttertoast.showToast(msg: "Login Successfully"),
Navigator.of(context)
.pushReplacementNamed(UploadScreen.routeName),
}).onError((e, s) {
Fluttertoast.showToast(msg: 'Incorrect Email or Password.',
toastLength: Toast.LENGTH_LONG
);
});
}
}
Future<dynamic> signIn(String email, String password) async {
if (_form.currentState!.validate()) {
print(email);
await _auth
.signInWithEmailAndPassword(email: email, password: password)
.then((uid) => {
Fluttertoast.showToast(msg: "Login Successfully"),
Navigator.of(context)
.pushNamed(UploadScreen.routeName), //change here
})
.catchError((e) {
Fluttertoast.showToast(msg: 'Incorrect Email or Password.',
toastLength: Toast.LENGTH_LONG
);
});
}
}
//Change in the return type make it dynamic

Flutter: flutter_local_notifications not work when running in Foreground

I want to implement FCM with flutter_local_notifications to handling notification from background and foreground. I already follow both documentation to setup the plugin. And when I try on Android, the background notification is work and show the notification. But when I try on foreground, the FCM is work (send the title and body), but the notification not show (get error). The detail error is bellow:
D/FLTFireMsgReceiver(26448): broadcast received for message
W/roonapp.stagin(26448): Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist, reflection, allowed)
W/roonapp.stagin(26448): Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist, reflection, allowed)
W/roonapp.stagin(26448): Accessing hidden method Landroid/os/WorkSource;->size()I (greylist, reflection, allowed)
W/roonapp.stagin(26448): Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
W/roonapp.stagin(26448): Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
[log] [32m——————————————————————————————————————————————————————————————————————
DEBUG
——————————————————————————————————————————————————————————————————————
2021-12-09T22:05:18.792141
——————————————————————————————————————————————————————————————————————
Show Notification:
Title -> test0
Body -> test0
Payload -> null
——————————————————————————————————————————————————————————————————————[0m
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.setAction(java.lang.String)' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:187)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1023)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1358)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1240)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:84)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:865)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at android.os.Looper.loop(Looper.java:197)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at android.app.ActivityThread.main(ActivityThread.java:7948)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/MethodChannel#dexterous.com/flutter/local_notifications(26448): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
E/flutter (26448): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.content.Intent android.content.Intent.setAction(java.lang.String)' on a null object reference, null, java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.setAction(java.lang.String)' on a null object reference
E/flutter (26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:187)
E/flutter (26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:1023)
E/flutter (26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:1358)
E/flutter (26448): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:1240)
E/flutter (26448): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/flutter (26448): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:84)
E/flutter (26448): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:865)
E/flutter (26448): at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (26448): at android.os.MessageQueue.next(MessageQueue.java:336)
E/flutter (26448): at android.os.Looper.loop(Looper.java:197)
E/flutter (26448): at android.app.ActivityThread.main(ActivityThread.java:7948)
E/flutter (26448): at java.lang.reflect.Method.invoke(Native Method)
E/flutter (26448): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/flutter (26448): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
E/flutter (26448): )
E/flutter (26448): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (26448): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (26448): <asynchronous suspension>
E/flutter (26448): #2 FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:194:7)
E/flutter (26448): <asynchronous suspension>
E/flutter (26448): #3 NotificationHelper.showNormalNotification (package:notification/notification/notifications_helper.dart:85:5)
E/flutter (26448): <asynchronous suspension>
E/flutter (26448):
Library Version
firebase_core: ^1.10.0
firebase_messaging: ^11.2.3
firebase_analytics: ^9.0.2
flutter_local_notifications: ^9.1.4
AndroidManifest.xml
<application
...>
<activity
android:showWhenLocked="true"
android:turnScreenOn="true">
...
</activity>
...
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="channel_id_app" />
</application>
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
...
await NotificationConfig.init();
runApp(App());
}
NotificationConfig
class NotificationConfig {
static init() async {
final notificationHelper = NotificationHelper();
try {
FirebaseMessaging.onBackgroundMessage(fcmBackgroundHandler); //This work fine
} catch (e, trace) {
Logger.e('Error Running Notification in Background: $e',
ex: e, stacktrace: trace);
}
//TODO: Foreground not work (the notification)
try {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
final notification = message.notification;
if (notification != null) {
final body = ReceivedNotification(
title: notification.title,
body: notification.body,
);
notificationHelper.showNormalNotification(body); //TODO: This is error when from `foreground`
}
});
} catch (e, trace) {
Logger.e('Error Running Notification in Foreground: $e',
ex: e, stacktrace: trace);
}
}
}
NotificationHelper
Future<void> fcmBackgroundHandler(RemoteMessage message) async {
final notificationHelper = NotificationHelper();
final body = ReceivedNotification(
title: message.notification?.title,
body: message.notification?.body,
);
await notificationHelper.showNormalNotification(body); //TODO: This is not error when from `background`
}
class NotificationHelper {
/// Singleton pattern
static NotificationHelper? _instance;
NotificationHelper._internal() {
_instance = this;
_init();
}
factory NotificationHelper() =>
_instance ?? NotificationHelper._internal();
final _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
Future<void> _init() async {
await _setupLocalNotification();
await _setupFcm();
}
Future<void> _setupLocalNotification() async {
const channel = AndroidNotificationChannel(
NotificationChannel.channelId,
NotificationChannel.channelName,
description: NotificationChannel.channelDesc,
importance: Importance.max,
);
/// Initialization Settings for Android
const initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
/// Initialization Settings for iOS
const initializationSettingsIOS = IOSInitializationSettings(
requestSoundPermission: false,
requestBadgePermission: false,
requestAlertPermission: false,
);
/// InitializationSettings for initializing settings for both platforms
const initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
await _flutterLocalNotificationsPlugin.initialize(
initializationSettings,
);
/// Create an Android Notification Channel.
///
/// We use this channel in the `AndroidManifest.xml` file to override the
/// default FCM channel to enable heads up notifications.
await _flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
}
Future<void> showNormalNotification(
ReceivedNotification? notification,
) async {
Logger.d(
'Show Notification:\n'
'Title -> ${notification?.title}\n'
'Body -> ${notification?.body}\n'
'Payload -> ${notification?.payload}\n',
);
await _flutterLocalNotificationsPlugin.show(
NotificationType.normal,
notification?.title,
notification?.body,
const NotificationDetails(
android: AndroidNotificationDetails(
NotificationChannel.channelId,
NotificationChannel.channelName,
channelDescription: NotificationChannel.channelDesc,
priority: Priority.high,
importance: Importance.max,
),
),
payload: notification?.payload,
);
}
Future<void> _setupFcm() async {
final fcm = FirebaseMessaging.instance;
await fcm.setForegroundNotificationPresentationOptions(
alert: true,
badge: true,
sound: true,
);
final token = await fcm.getToken();
Logger.d("Token FCM: $token");
...
}
}
As you can see above, both Foreground and Background call some function notificationHelper.showNormalNotification(body). But when it's from Foreground getting error like in the above logcat, and when from Background it's work.
What I miss to setup flutter_local_notifications to work's when running in Foreground?
Finally, after spend 2 days of work I found my solution.
The notification not show when app is open or running in foreground it's because in my AndroidManifest.xml have intent service for deeplink.
<intent-filter>
....
<data android:scheme="${deeplink_schema}" />
</intent-filter>