i’ve carried out one utility which helps firebase notifications My app labored high-quality earlier than. however once I merge my notification department, my app stops working. when i launch my utility on iOS, it reveals this error
Connecting to VM Service at ws://127.0.0.1:49769/gMyOshYEY=/ws
flutter: dependOnInheritedWidgetOfExactType() or dependOnInheritedElement() was referred to as earlier than _LoginScreenState.initState() was accomplished.
When an inherited widget modifications, for instance, if the worth of Theme.of() modifications, its dependent widgets are rebuilt. If the dependent widget’s reference to the inherited widget is in a constructor or an initState() methodology, then the rebuilt dependent widget is not going to mirror the modifications within the inherited widget.
Usually, references to inherited widgets ought to happen in widget construct() strategies. Alternatively, initialization based mostly on inherited widgets will be positioned within the didChangeDependencies methodology, which is named after initState and at any time when the dependencies change thereafter.
flutter: [core/no-app] No Firebase App ‘[DEFAULT]’ has been created.
and when i reload my utility, i get this error
═ Exception caught by widgets library ═══════════════════════════════════
The next FirebaseException was thrown constructing _InheritedProviderScope<BannersBloc?>(worth: ):
[core/no-app] No Firebase App ‘[DEFAULT]’ has been created – name Firebase.initializeApp()
The related error-causing widget was:
BlocProvider BlocProvider:file:///Customers/admin/Paperwork/NadiTarangini/nt_guna/lib/important.dart:196:48
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (bundle:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:193:5)
method_channel_firebase.dart:193
#1 Firebase.app (bundle:firebase_core/src/firebase.dart:56:41)
firebase.dart:56
#2 FirebaseMessaging.occasion (bundle:firebase_messaging/src/messaging.dart:32:47)
messaging.dart:32
#3 new NotificationManager (bundle:nadi_tarangini/DashboardScreen/AppBar/notification/controller/notification_manager.dart:18:66)
notification_manager.dart:18
#4 new _DashboardState (bundle:nadi_tarangini/DashboardScreen/screens/dashboard.dart:48:51)
dashboard.dart:48
#5 Dashboard.createState (bundle:nadi_tarangini/DashboardScreen/screens/dashboard.dart:40:37)
dashboard.dart:40
#6 new StatefulElement (bundle:flutter/src/widgets/framework.dart:5564:25)
framework.dart:5564
#7 StatefulWidget.createElement (bundle:flutter/src/widgets/framework.dart:776:38)
framework.dart:776
... Regular component mounting (7 frames)
#14 _InheritedProviderScopeElement.mount (bundle:supplier/src/inherited_provider.dart:411:11)
inherited_provider.dart:411
... Regular component mounting (7 frames)
#21 SingleChildWidgetElementMixin.mount (bundle:nested/nested.dart:222:11)
however it’s working good in my android utility
right here is my code
@pragma('vm:entry-point')
Record<NotificationModel> notificationsList = [];
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
Deal with background messages right here
String? notificationTitle = message.notification?.title;
String? notificationBody = message.notification?.physique;
if (notificationTitle != null && notificationBody != null) {
notificationsList = await NotificationManager().getNotificationsFromApi();
int badgeCount = notificationsList.the place((n) =>!n.isRead). size;
FlutterAppBadger.updateBadgeCount(badgeCount);
sendNotificationUnreadCount.add({'badgeCount': badgeCount, 'notifications': notificationsList});
}
}
MaterialColor appclr = const MaterialColor(
0xFF00B3DC, // The first worth of the colour
<int, Coloration>{
50: Coloration (0xFFE6F7FB), // Shade 50
100: Coloration (0xFFB3E2F0), // Shade 100
200: Coloration (0xFF80CCE6), // Shade 200
300: Coloration (0xFF4DA7DB), // Shade 300
400: Coloration (0xFF267EA3), // Shade 400
500: Coloration (0xFF00B3DC), // Shade 500 (the first colour)
600: Coloration (0xFF008FA7), // Shade 600
700: Coloration (0xFF00728B), // Shade 700
800: Coloration (0xFF00566F), // Shade 800
900: Coloration (0xFF003A54), // Shade 900
},
);
void important() async {
WidgetsFlutterBinding.ensureInitialized();
ByteData information =
await PlatformAssetBundle().load('belongings/ca/lets-encrypt-r3.pem');
closing context = SecurityContext.defaultContext;
context.setTrustedCertificatesBytes(information.buffer.asUint8List());
context.allowLegacyUnsafeRenegotiation = true;
HttpOverrides.international = MyHttpOverrides();
attempt {
await Firebase.initializeApp();
// FirebaseMessaging.occasion.setForegroundNotificationPresentationOptions(
// alert: true, badge: true, sound: true);
// log("Firebase Initialized");
} catch (e) {
// print("Firebase initialization failed: $e");
}
Bloc.observer = MyBlocObserver();
runApp(const MyApp());
}
class MyHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext? context) {
return tremendous.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
}
class MyApp extends StatelessWidget {
const MyApp({tremendous.key});
@override
Widget construct(BuildContext context) {
return MultiBlocProvider(
suppliers: [
// BlocProvider<AppBarBloc>(
// create: (context) => AppBarBloc(context: context)),
BlocProvider<BannersBloc>(
create: (context) => BannersBloc(context: context)),
BlocProvider<ReferralsBloc>(
create: (context) => ReferralsBloc(context: context)
BlocProvider<BlogsBloc>(
create: (context) => BlogsBloc(context: context)),
BlocProvider<AppointmentBloc>(
create: (context) => AppointmentBloc(context: context)),
BlocProvider<IconContainerBloc>(
create: (context) => IconContainerBloc(context: context)),
BlocProvider<PatientScreenBloc>(
create: (context) => PatientScreenBloc(context: context)),
// Add more BlocProviders if needed
],
little one: Sizer(
builder: (context, orientation, deviceType) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Nadi Tarangini',
navigatorKey: AppNavigator.navigatorKey,
theme: ThemeData(
primarySwatch: appclr,
useMaterial3: false,
fontFamily: 'Roboto-Daring',
appBarTheme: const AppBarTheme(
backgroundColor:
ColorConstants.ntBlue, // Set the worldwide AppBar colour right here
),
),
initialRoute: "/",
onGenerateRoute: (RouteSettings settings) {
if (settings.identify == RecipeScreen.routeName) {
closing Map<String, dynamic> information =
settings.arguments as Map<String, dynamic>;
return MaterialPageRoute(builder: (context) {
return RecipeScreen(recipeData: information);
});
}
return null;
},
routes: {
"/": (context) => const SplashScreen(),
"/OnboardingScreen": (context) => const OnboardingScreen(),
"/SignUpOnboardingScreen": (context) =>
const SignUpOnboardingScreen(),
"/PersonalScreen": (context) => const PersonalScreen(),
"/ProfessionalScreen": (context) => const ProfessionalScreen(),
"/ClinicScreen": (context) => const ClinicScreen(),
"/CredentialScreen": (context) => const CredentialScreen(),
"/LoginScreen": (context) => const LoginScreen(),
"/OtpVerificationScreen": (context) =>
const OtpVerificationScreen(),
"/ForgotPasswordScreen": (context) =>
const ForgotPasswordScreen(),
"/CreateAccountScreen": (context) => const CreateAccountScreen(),
"/ClinicDetailsScreen": (context) => const ClinicDetailsScreen(),
"/SyncScreen": (context) => const SyncScreen(),
"/SettingsScreen": (context) => const SettingsScreen(),
"/LinkDeviceScreen": (context) => const LinkDeviceScreen(),
"/DeviceSubscription": (context) => const DeviceSubscription(),
"/HelpScreen": (context) => const HelpScreen(),
// "/DashboardScreen": (context) => const DashboardScreen(),
"/DashboardScreen": (context) => BlocProvider(
create: (context) => BannersBloc(context: context),
little one: const Dashboard(),
),
"/PatientsScreen": (context) => const PatientsScreen(),
"/PatientScreen": (context) => const PatientListScreen(),
"/PatientQueriesScreen": (context) =>
const PatientQueriesScreen(),
"/AddPatientScreen": (context) => const AddPatientScreen(),
"/NadiCaptureScreen": (context) => const NadiParikshaScreen(),
"/NadiDisplayScreen": (context) => const NadiDisplayScreen(),
"/AppointmentViewScreen": (context) =>
const AppointmentViewScreen(),
// "/AppointmentDiaryScreen": (context) => const AppointmentDiaryScreen(),
"/UpdateDoctorDetailsScreen": (context) =>
const UpdateDoctorDetailsScreen(),
"/AddAppointmentScreen": (context) =>
const AddAppointmentScreen(),
"/PendingAppointmentScreen": (context) =>
const PendingAppointmentScreen(),
"/MissedAppointmentScreen": (context) =>
const MissedAppointmentScreen(),
"/EditAppointmentScreen": (context) =>
const EditAppointmentScreen(),
"/AppointmentHistoryScreen": (context) =>
const AppointmentHistoryScreen(),
"/NotificationScreen": (context) => NotificationScreen(),
///Patinet Routes
"/PatientRegistrationScreen": (context) =>
const PatientRegistrationScreen(),
"/PatientsHomeScreen": (context) => const PatientsHomeScreen(),
"/UpdatePatientDetailsScreen": (context) =>
const UpdatePatientDetailsScreen(),
"/ReferralHistory": (context) => const ReferralHistory(),
"/EditPatient": (context) => const EditAllDataPatient(),
"/EditAnonymousPatient": (context) => const EditAnonymous(),
"/DrawerMenu": (context) => DrawerMenu(),
"/ChangePasswordScreen": (context) =>
const ChangePasswordScreen(),
},
);
},
),
);
}
}
that is my notification supervisor class
closing FirebaseMessaging _firebaseMessaging = FirebaseMessaging.occasion;
closing FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Record<NotificationModel> notificationsList = [];
// Generate a singular notification ID based mostly on the present timestamp
int badgeCount = 0; // Add badgeCount variable
closing Record<Perform(dynamic)> _listeners = [];
void addNotificationListener(Perform(dynamic) listener) {
_listeners.add(listener);
}
void removeNotificationListener(Perform(dynamic) listener) {
_listeners.take away(listener);
}
void notifyListeners(dynamic notification) {
for (closing listener in _listeners) {
listener(notification);
}
}
void init() {
// Initialize FlutterLocalNotificationsPlugin
const initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
DarwinInitializationSettings initializationSettingsDarwin =
const DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
defaultPresentBanner: true,
);
closing initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsDarwin);
flutterLocalNotificationsPlugin.initialize(
initializationSettings,
// onDidReceiveBackgroundNotificationResponse: (particulars) {
// Navigator.pushNamedAndRemoveUntil(
// AppNavigator.navigatorKey.currentContext!,
// "/AppointmentViewScreen",
// (route) => false);
// },
onDidReceiveNotificationResponse: (particulars) async {
Record<NotificationModel> navNotifications = await getNotificationsFromApi();
// print("print obtain: ${ModalRoute.of(AppNavigator.navigatorKey.currentContext!)}");
// Navigator.of( AppNavigator.navigatorKey.currentContext!,).pushAndRemoveUntil(MaterialPageRoute(builder: (context) =>
// NotificationScreen(notifications: navNotifications)), (Route<dynamic> route) => false);
// print("all particulars $particulars");
if (particulars.payload?.comprises("appointment")?? false) {
Navigator.pushNamedAndRemoveUntil(
AppNavigator.navigatorKey.currentContext!,
"/AppointmentViewScreen",
(route) => false);
}else{
Navigator.pushAndRemoveUntil<void>(
AppNavigator.navigatorKey.currentContext!,
MaterialPageRoute<void>(builder: (BuildContext context) => NotificationScreen(notifications: navNotifications)),
ModalRoute.withName('/DashboardScreen'),
);
}
},
);
// Request permission to obtain notifications
_firebaseMessaging.requestPermission();
// Deal with notifications when the app is within the foreground
FirebaseMessaging.onMessage.hear((RemoteMessage message) async {
_handleNotification(message,false);
print("foreground");
});
// Deal with notifications when the app is within the background and opened by the person
FirebaseMessaging.onMessageOpenedApp.hear((RemoteMessage message) async {
_handleNotification(message,true);
print("background");
});
// Initialize badge depend
FlutterAppBadger.updateBadgeCount(0);
// Register the background message handler
FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
// Retrieve the FCM token
_firebaseMessaging.getToken().then((String? token) {
if (kDebugMode) {
print("FCM Token: $token");
}
});
}
Future<Record<NotificationModel>> getNotificationsFromApi() async {
attempt {
closing response = await ApiProvider().fetchNotificationsData(context: AppNavigator.navigatorKey.currentContext!);
closing Record<dynamic> jsonList = response['notifications_data'];
Record<NotificationModel> notifications = jsonList.map((json) => NotificationModel.fromJson(json)).toList();
notifications.kind((a, b) => b.timestamp.compareTo(a.timestamp));
notifications = notifications;
return notifications;
} catch (e) {
if (kDebugMode) {
print('Error fetching notifications: $e');
}
return [];
}
}
void _handleNotification(RemoteMessage message,bool navigate) async {
bool appAlreadyOpen = isAppAlreadyOpen();
print("is app open: $appAlreadyOpen");
String? notificationType = message.information['notification_type'] ?? '';
String? notificationTitle = message.notification?.title;
String? notificationBody = message.notification?.physique;
if (notificationTitle != null && notificationBody != null) {
// Show the notification within the system tray
const androidPlatformChannelSpecifics = AndroidNotificationDetails(
'nadi_tarangini',
'nadi_tarangini_notifications',
significance: Significance.excessive,
precedence: Precedence.excessive,
);
const platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
);
int notificationId = DateTime.now().millisecondsSinceEpoch ~/ 1000;
// Create a NotificationModel object
closing newNotification = NotificationModel(
id: notificationId,
title: notificationTitle,
physique: notificationBody,
sort: notificationType!,
timestamp: DateTime.now(),
);
// Add the notification to the listing
// notifications = await getNotificationsFromApi();
notificationsList.add(newNotification);
await updateDashboardNotificationCount();
await flutterLocalNotificationsPlugin.present(
notificationId,
notificationTitle,
notificationBody,
platformChannelSpecifics,
payload: notificationBody,
);
if (kDebugMode) {
print("Obtained Notification: $notificationTitle - $notificationBody");
}
if (notificationBody.comprises("appointment") && navigate) {
Navigator.pushNamedAndRemoveUntil(
AppNavigator.navigatorKey.currentContext!,
"/AppointmentViewScreen",
(route) => false);
} else if (navigate) {
Navigator.pushAndRemoveUntil<void>(
AppNavigator.navigatorKey.currentContext!,
MaterialPageRoute<void>(builder: (BuildContext context) => NotificationScreen(notifications: notifications)),
ModalRoute.withName('/DashboardScreen'));
// AppNavigator.navigatorKey.currentContext!,
// MaterialPageRoute(
// builder: (context) => NotificationScreen(
// notifications: notifications,
// ),
// ),
// );
}
}
}
Future<void> markNotificationAsRead(Record<NotificationModel> notifications,
int notificationId, int index) async {
if (index != -1 && !notifications[index].isRead) {
notifications[index].isRead = true;
await ApiProvider().markNotificationAsUnreadForDoc(
context: AppNavigator.navigatorKey.currentContext!,
notificationId: notificationId,
);
await updateDashboardNotificationCount();
}
}
Future<void> updateDashboardNotificationCount() async {
Record<NotificationModel> notifications = await getNotificationsFromApi();
badgeCount = notifications.the place((n) => !n.isRead).size;
FlutterAppBadger.updateBadgeCount(badgeCount);
sendNotificationUnreadCount.add({'badgeCount': badgeCount, 'notifications': notifications});
}
bool isAppAlreadyOpen() {
return RendererBinding.occasion.hasScheduledFrame;
}```
[1]: https://i.stack.imgur.com/ZjH56.jpg