Flutter "globaloverlay.support()" doesn't work when its on material app - flutter

Well the problem I am having here, normally if I wrap materialApp with global overlay support, it should be working, but it is not as you can see from debug console. Any suggestions? I am normally trying integrate firebase on iOS. The restart app is causing problem I guess, but I do not want to throw it out, to saying truth
// ignore_for_file: prefer_const_constructors, duplicate_ignore
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:medicte/pages/home_page.dart';
import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:page_transition/page_transition.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (kDebugMode) {
print("Handling a background message: ${message.messageId}");
}
}
main() {
runApp(RestartWidget(child: MyApp()));
}
Future<void> initializeDefault() async {
FirebaseApp app = await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
if (kDebugMode) {
print('Initialized default app $app');
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// ignore: prefer_const_constructors
return ScreenUtilInit(
designSize: const Size(428, 926),
builder: (context, child) => OverlaySupport.global(
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: SplashScreen(),
),
),
);
}
}
class RestartWidget extends StatefulWidget {
const RestartWidget({Key? key, required this.child}) : super(key: key);
final Widget child;
static void restartApp(BuildContext context) {
context.findAncestorStateOfType<_RestartWidgetState>()?.restartApp();
}
#override
// ignore: library_private_types_in_public_api
_RestartWidgetState createState() => _RestartWidgetState();
}
class _RestartWidgetState extends State<RestartWidget> {
late final FirebaseMessaging _messaging;
PushNotification? _notificationInfo;
void requestAndRegisterNotification() async {
// 1. Initialize the Firebase app
await initializeDefault();
// 2. Instantiate Firebase Messaging
_messaging = FirebaseMessaging.instance;
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
// 3. On iOS, this helps to take the user permissions
NotificationSettings settings = await _messaging.requestPermission(
alert: true,
badge: true,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
if (kDebugMode) {
print('User granted permission');
}
String? token = await _messaging.getToken();
if (kDebugMode) {
print("The token is ${token!}");
}
// For handling the received notifications
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Parse the message received
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
if (kDebugMode) {
print("The notification is $notification");
}
setState(() {
_notificationInfo = notification;
});
if (_notificationInfo != null) {
// For displaying the notification as an overlay
showSimpleNotification(
Text(_notificationInfo!.title!),
subtitle: Text(_notificationInfo!.body!),
background: Colors.cyan.shade700,
duration: Duration(seconds: 2),
);
}
});
} else {
if (kDebugMode) {
print('User declined or has not accepted permission');
}
}
}
#override
void initState() {
requestAndRegisterNotification();
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
setState(() {
_notificationInfo = notification;
});
});
super.initState();
}
Key key = UniqueKey();
void restartApp() {
setState(() {
key = UniqueKey();
});
}
#override
Widget build(BuildContext context) {
return KeyedSubtree(
key: key,
child: widget.child,
);
}
}
class SplashScreen extends StatelessWidget {
const SplashScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return AnimatedSplashScreen(
splash: Image.asset(
'lib/images/MedicteLogo-4a2e31cd2358bb08ff8d12acb2761357.png'),
nextScreen: HomePage(),
splashTransition: SplashTransition.scaleTransition,
pageTransitionType: PageTransitionType.rightToLeftWithFade,
);
}
}
class PushNotification {
PushNotification({
this.title,
this.body,
});
String? title;
String? body;
}
Heading
This is my debug console:
>2022-09-02 12:02:26.023971+0300 Runner[19573:866637] Metal API Validation Enabled
2022-09-02 12:02:26.194783+0300 Runner[19573:866637] Could not load the "LaunchImage" image referenced from a nib in the bundle with identifier "com.example.medicte"
2022-09-02 12:02:26.208267+0300 Runner[19573:866829] 9.4.0 - [FirebaseCore][I-COR000012] Could not locate configuration file: 'GoogleService-Info.plist'.
2022-09-02 12:02:26.236111+0300 Runner[19573:866823] 9.4.0 - [FirebaseCore][I-COR000003] The default Firebase app has not yet been configured. Add `FirebaseApp.configure()` to your application initialization. This can be done in in the App Delegate's application(_:didFinishLaunchingWithOptions:)` (or the `#main` struct's initializer in SwiftUI). Read more: https:/goo.gl/ctyzm8.
2022-09-02 12:02:26.237231+0300 Runner[19573:866823] 9.4.0 - [FirebaseCore][I-COR000003] The default Firebase app has not yet been configured. Add `FirebaseApp.configure()` to your application initialization. This can be done in in the App Delegate's application(_:didFinishLaunchingWithOptions:)` (or the `#main` struct's initializer in SwiftUI). Read more: https:/goo.gl/ctyzm8.
2022-09-02 12:02:26.279437+0300 Runner[19573:866849] flutter: The Dart VM service is listening on http://127.0.0.1:51958/HXJzT6ZmSJY=/
2022-09-02 12:02:26.614633+0300 Runner[19573:866825] 9.4.0 - [FirebaseCore][I-COR000005] No app has been configured yet.
2022-09-02 12:02:26.836889+0300 Runner[19573:866830] 9.4.0 - [FirebaseCore][I-COR000005] No app has been configured yet.
2022-09-02 12:02:26.912218+0300 Runner[19573:866823] 9.4.0 - [FirebaseMessaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging
to ensure proper integration.
2022-09-02 12:02:26.922498+0300 Runner[19573:866833] flutter: Initialized default app FirebaseApp([DEFAULT])
2022-09-02 12:02:26.922884+0300 Runner[19573:866823] 9.4.0 - [FirebaseMessaging][I-FCM002022] APNS device token not set before retrieving FCM Token for Sender ID '204532241696'. Notifications to this FCM Token will not be delivered over APNS.Be sure to re-retrieve the FCM token once the APNS device token is set.
2022-09-02 12:02:27.019553+0300 Runner[19573:866833] flutter: User granted permission
2022-09-02 12:02:29.000587+0300 Runner[19573:866833] flutter: The token is c1P2bEEh9Et3njcfkiOntp:APA91bFZIAR4oxrrwi0aJuYVofPC93x6wjy39TCTUt8-w6PkxtDgKTQUv-iQamhnd_pox6q2mm4JvBD6hSBS3bWmbzp8BO0LhpR89PvMwJv5ZdPWokguVkpMW6t5YUdIfVPwhlfTpsY5
2022-09-02 12:02:38.677058+0300 Runner[19573:866833] flutter: The notification is Instance of 'PushNotification'
2022-09-02 12:02:38.681029+0300 Runner[19573:866833] [VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: 'package:overlay_support/src/overlay_state_finder.dart': Failed assertion: line 12 pos 7: '_debugInitialized': Global OverlaySupport Not Initialized !
ensure your app wrapped widget OverlaySupport.global
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:51:61)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:40:5)
#2 findOverlayState (package:overlay_support/src/overlay_state_finder.dart:12:7)
#3 showOverlay (package:overlay_support/src/overlay.dart:63:26)
#4 showOverlayNotification (package:overlay_support/src/notification/overlay_notification.dart:21:10)
#5 showSimpleNotification (package:overlay_support/src/notification/overlay_notification.dart:97:17)
#6 _RestartWidgetState.requestAndRegisterNotification.<anonymous closure> (package:medicte/main.dart:106:11)
#7 _rootRunUnary (dart:async/zone.dart:1434:47)
#8 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#9 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
#10 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
#11 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
#12 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
#13 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
#14 _rootRun (dart:async/zone.dart:1418:47)
#15 _CustomZone.run (dart:async/zone.dart:1328:19)
#16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
#18 _rootRun (dart:async/zone.dart:1426:13)
#19 _CustomZone.run (dart:async/zone.dart:1328:19)
#20 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#21 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
#22 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#23 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)

Actually, error is Could not locate configuration file: 'GoogleService-Info.plist'.
If you didn't initialize the Firebase project, start with and follow this doc
firebase init
After all done, you will find

Related

Flutter Material App error on debug when switching scene

I was making 2 scene with google Maps and drawing polyline on the map, the apps have no problem running and everything working fine, however on the debug there is this big stack of error in debug which I have no idea what it meant, can anyone tell me what is this ? It is kind of concerning for me
Below is the error on the debug,
════════ Exception caught by rendering library ═════════════════════════════════
Failed to rasterize a picture: unable to create render target at specified size.
The callstack when the image was created was:
#0 new Image._.<anonymous closure> (dart:ui/painting.dart:1670:32)
#1 new Image._ (dart:ui/painting.dart:1672:6)
#2 Scene.toImageSync (dart:ui/compositing.dart:34:18)
#3 OffsetLayer.toImageSync
layer.dart:1497
#4 _RenderSnapshotWidget._paintAndDetachToImage
snapshot_widget.dart:315
#5 _RenderSnapshotWidget.paint
snapshot_widget.dart:345
#6 RenderObject._paintWithContext
object.dart:2853
#7 PaintingContext.paintChild
object.dart:253
#8 RenderProxyBoxMixin.paint
#9 _ZoomEnterTransitionPainter.paint
page_transitions_theme.dart:866
#10 _RenderSnapshotWidget.paint
snapshot_widget.dart:335
#11 RenderObject._paintWithContext
object.dart:2853
#12 PaintingContext.paintChild
object.dart:253
#13 RenderProxyBoxMixin.paint
proxy_box.dart:144
#14 _ZoomExitTransitionPainter.paint
page_transitions_theme.dart:938
#15 _RenderSnapshotWidget.paint
snapshot_widget.dart:335
#16 RenderObject._paintWithContext
object.dart:2853
#17 PaintingContext.paintChild
object.dart:253
#18 RenderProxyBoxMixin.paint
proxy_box.dart:144
#19 _ZoomEnterTransitionPainter.paint
page_transitions_theme.dart:866
#20 _RenderSnapshotWidget.paint
snapshot_widget.dart:335
#21 RenderObject._paintWithContext
object.dart:2853
#22 PaintingContext.paintChild
object.dart:253
#23 RenderProxyBoxMixin.paint
proxy_box.dart:144
#24 RenderObject._paintWithContext
object.dart:2853
#25 PaintingContext._repaintCompositedChild
object.dart:169
#26 PaintingContext.repaintCompositedChild
object.dart:112
#27 PipelineOwner.flushPaint
object.dart:1137
#28 RendererBinding.drawFrame
binding.dart:518
#29 WidgetsBinding.drawFrame
binding.dart:865
#30 RendererBinding._handlePersistentFrameCallback
binding.dart:381
#31 SchedulerBinding._invokeFrameCallback
binding.dart:1289
#32 SchedulerBinding.handleDrawFrame
binding.dart:1218
#33 SchedulerBinding._handleDrawFrame
binding.dart:1076
#34 _invoke (dart:ui/hooks.dart:145:13)
#35 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:338:5)
#36 _drawFrame (dart:ui/hooks.dart:112:31)
The relevant error-causing widget was
MaterialApp
Edit:
Here's the packages and code of the scene that triggered the error in the debug, for extra information, the error did not triggered consistently. I have no idea what trigered it, the materialapp exist on the home page. I use navigator function to switch scene
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_in_flutter/location_service.dart';
import 'package:geolocator/geolocator.dart';
import 'package:label_marker/label_marker.dart';
StreamSubscription<Position>? userStreamlocation;
Position? streamResult;
class navScreen extends StatefulWidget
{
final String userOrigin;
final String userGoal;
navScreen({Key? mykey, required this.userOrigin, required this.userGoal});
#override
State<navScreen> createState ()=>nav_Screen(userOrigin: userOrigin, userGoal: userGoal);
}
class geostracking
{
Future<Position> determineLocation() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location Service are Disabled');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location Permission Denied');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error('Permission Denied Forever');
}
Position position = await Geolocator.getCurrentPosition();
print(position);
return position;
}
Position? listenToLocation()
{
Position? userposition;
final LocationSettings _locationSettings = LocationSettings(accuracy: LocationAccuracy.high,distanceFilter: 100);
userStreamlocation = Geolocator.getPositionStream(locationSettings: _locationSettings).listen(
(userposition) {
print(userposition == null ? 'Unknown' : '${userposition.latitude.toString()}, ${userposition.longitude.toString()}');
setState(){
streamResult=userposition;
}
});
return userposition;
}
}
class nav_Screen extends State<navScreen>
{
StreamSubscription<Position>? streamPosition;
#override
void dispose()
{
super.dispose();
streamPosition?.cancel();
}
late GoogleMapController mapController;
final String userOrigin;
final String userGoal;
nav_Screen({required this.userOrigin,required this.userGoal, });
final LatLng _kGooglePlex = LatLng(baseLat, baseLong);
Set<Marker> _markers = Set<Marker>();
Set<Polyline> _navPolylines =Set<Polyline>();
int _polylineIdCounter=0;
int markerNumber=1;
int _markerIDCounter = 1;
void _setMarker(String ID, var Place) {
String markerLabel;
if(markerNumber==1)
{
markerLabel = 'Start';
}
else
{
markerLabel = "Destination";
}
setState(() {
_markers.addLabelMarker(LabelMarker(
backgroundColor: Color.fromARGB(255, 0, 8, 255),
label: markerLabel,
markerId: MarkerId(ID),
position: LatLng(Place['geometry']['location']['lat'],
Place['geometry']['location']['lng']),)
);
_markerIDCounter++;
markerNumber++;
});
}
void _setPolylines(List<PointLatLng> points) {
final String _navPolylinesID = 'polyline_$_polylineIdCounter';
//print('Check : '+points.toString());
_navPolylines.add(
Polyline(
polylineId: PolylineId(_navPolylinesID),
width: 5,
color: Color.fromARGB(255, 56, 12, 255),
startCap: Cap.roundCap,
endCap: Cap.buttCap,
visible: true,
points: points
.map((point) => LatLng(point.latitude, point.longitude)).toList(),
)
);_polylineIdCounter++;
}
void _onMapCreated(GoogleMapController controller) async {
mapController = controller;
var direction = await LocationService().getDirectionNoWP(userOrigin, userGoal);
print(_polylineIdCounter);
_setPolylines(direction['polyline_decoded']);
String OplaceID = await LocationService().getPlaceID(userOrigin);
var Oplace = await LocationService().getPlace(userOrigin);
_setMarker(OplaceID, Oplace);
String DplaceID = await LocationService().getPlaceID(userGoal);
var Dplace = await LocationService().getPlace(userGoal);
_setMarker(DplaceID, Dplace);
setState(() {});
}
#override
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(title: Text('Test')),
body: Column
(children: [
Expanded(
child:
GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: _kGooglePlex,zoom: 10),
markers: _markers,
polylines: _navPolylines,
onMapCreated: _onMapCreated,
)
),
]),
floatingActionButton: Container(alignment: Alignment.bottomCenter,
child: FloatingActionButton(onPressed: ()async{
geostracking().listenToLocation();
},
child: Icon(Icons.navigation),),
),
);
}
}
Here's a snip of the main page code and it's packages
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_in_flutter/current_location.dart';
import 'package:google_maps_in_flutter/customer_profile.dart';
import 'package:google_maps_in_flutter/location_service.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:geolocator/geolocator.dart';
import 'package:label_marker/label_marker.dart';
void main() => runApp(MyApp());
StreamSubscription<Position>? userStreamlocation;
Position? streamResult;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Google Map Test',
home: GMap(),
//routes: ,
);
}
}
class GMap extends StatefulWidget {
#override
State<GMap> createState() => GMapState();
}
class requestTemplateConverter{
class GMapState extends State<GMap> {

Unhandled Exception: setState() called after dispose()

I am trying to receive notifications in my flutter app using Firebase Messaging to display them in the app, but I keep getting the error:
/FLTFireMsgReceiver( 6823): broadcast received for message
E/flutter ( 6823): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called after dispose(): _TipsState#aa4df(lifecycle state: defunct, not mounted)
E/flutter ( 6823): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 6823): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 6823): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 6823): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1085:9)
E/flutter ( 6823): #1 State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter ( 6823): #2 _TipsState.getNotification.<anonymous closure> (package:stock_baba/Screens/Tips.dart:38:9)
E/flutter ( 6823): #3 _rootRunUnary (dart:async/zone.dart:1434:47)
E/flutter ( 6823): #4 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
E/flutter ( 6823): #5 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
E/flutter ( 6823): #6 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
E/flutter ( 6823): #7 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
E/flutter ( 6823): #8 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
E/flutter ( 6823): #9 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
E/flutter ( 6823): #10 _rootRun (dart:async/zone.dart:1418:47)
E/flutter ( 6823): #11 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 6823): #12 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 6823): #13 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 6823): #14 _rootRun (dart:async/zone.dart:1426:13)
E/flutter ( 6823): #15 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 6823): #16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 6823): #17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 6823): #18 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 6823): #19 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
The PushNotification class is a simple class with the string fields title, body, dataTitle and dataBody.
My code is as follows:
class _TipsState extends State<Tips> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
final List<PushNotification> messages = [];
PushNotification? _notificationInfo;
#override
void initState() {
getNotification();
super.initState();
}
void getNotification() async {
NotificationSettings settings =
await _firebaseMessaging.requestPermission();
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print("Permission granted!");
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
dataTitle: message.data['title'],
dataBody: message.data['body']);
setState(() {
_notificationInfo = notification;
});
if (notification != null) {
showSimpleNotification(Text(_notificationInfo!.title!),
duration: Duration(seconds: 2),
subtitle: Text(_notificationInfo!.body!));
}
print(notification);
print(message.data);
});
} else {
print("Permission declined!");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: messages.isEmpty
? Container()
: ListView(
children: [Text(messages[0].title!)],
),
);
}
}
I tried wrapping my setState() with mounted() but it didn't work.
How can I resolve this issue and display the incoming notifications in my app?
Cancel the Stream after dispose it
Create StreamSubscription variable
StreamSubscription messagingSubscription;
Assign variable to your listen
....
messagingSubscription = FirebaseMessaging.onMessage.listen((RemoteMessage message) {
Dispose your StreamSubscription
#override
void dispose() {
messagingSubscription?.cancel();
super.dispose();
}
here is my code and its in working ..copy the code and make a dart class and paste it . your notification start working
use there plugins
firebase_core: ^1.11.0
firebase_messaging: ^11.2.5
flutter_local_notifications: ^9.2.0
import 'dart:convert';
import 'dart:math';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:vcare/firebase_options.dart';
class NotificationHelper {
NotificationDetails get _ongoing {
const androidChannelSpecifics = AndroidNotificationDetails(
'customer-channel-id',
'customer-channel-name',
importance: Importance.max,
priority: Priority.high,
ongoing: false,
autoCancel: true,
);
const iOSChannelSpecifics = IOSNotificationDetails();
return const NotificationDetails(android: androidChannelSpecifics, iOS: iOSChannelSpecifics);
}
// Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
// await initFirebase();
// }
configure() async {
await initFirebase();
FirebaseMessaging messaging = FirebaseMessaging.instance;
await requestPermission(messaging);
final String? token = await messaging.getToken();
// FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
final notification = await setupLocalNotification();
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
showNotification(
notification,
title: message.notification?.title,
body: message.notification?.body,
payload: message.data,
type: _ongoing,
);
});
return token;
}
Future<void> requestPermission(FirebaseMessaging messaging) async {
await messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
}
Future<void> initFirebase() async {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
}
setupLocalNotification() async {
const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings(
'notification_icon',
);
final IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: (int id, String? title, String? body, String? payload) {},
);
final InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
iOS: initializationSettingsIOS,
);
var notification = FlutterLocalNotificationsPlugin();
await notification.initialize(initializationSettings, onSelectNotification: (_) {});
return notification;
}
showNotification(FlutterLocalNotificationsPlugin notifications,
{required String? title, required String? body, required NotificationDetails type, required payload}) {
notifications.show(Random().nextInt(100), title, body, type, payload: json.encode(payload ?? {}));
}
}
and then call this class in main.dart file here is the code
WidgetsFlutterBinding.ensureInitialized();
String? token = await NotificationHelper().configure();
_storeFCMToken(token);
print("deviceToken $token");
if you find any problem please let me know. if you find this code is helping you .then please mark my answer as accepted

keep getting "Null check operator used on a null value" error. i've checked my code 100 times

keep getting "Null check operator used on a null value" error
actually im trying to use providers to get values from database and use em in my app
but im stuck at this i checked my code in every single way but still i keep getting this error
:lib\providers\user_provider.dart
import 'package:flutter/widgets.dart';
import 'package:test_app/models/user.dart';
import 'package:test_app/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
lib\pages\home.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_app/providers/user_provider.dart';
import 'package:test_app/models/user.dart' as model;
// import 'dart:html';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
void initState() {
super.initState();
addData();
}
addData() async {
UserProvider _userProvider =
Provider.of<UserProvider>(context, listen: false);
await _userProvider.refreshUser();
}
#override
Widget build(BuildContext context) {
model.User user = Provider.of<UserProvider>(context).getUser;
return Scaffold(
body: Center(
child: Text("this is homepage"),
),
);
}
}
debug snippet
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following _CastError was thrown building Home(dirty, dependencies:
[_InheritedProviderScope<UserProvider?>], state: _HomeState#17895):
Null check operator used on a null value
The relevant error-causing widget was:
Home Home:file:///C:/Users/abc/Desktop/flutter/test_app/lib/main.dart:53:34
When the exception was thrown, this was the stack:
#0 UserProvider.getUser (package:test_app/providers/user_provider.dart:9:28)
#1 _HomeState.build (package:test_app/pages/home.dart:36:59)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4870:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4735:5)
#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4919:11)
#8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4729:5)
#9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#10 Element.updateChild (package:flutter/src/widgets/framework.dart:3524:20)
#11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4780:16)
#12 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#13 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#15 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#16 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#17 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#18 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#19 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:862:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
idk what the problem actually im new to flutter and dart
i've using python for my whole life
refreshUser is a future and it sets _user but because you're calling getUser IMMEDIATELY build method, which basically returns _user as a non-null value, the error would be thrown.
Try this:
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User? get getUser => _user;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
And your _HomeState:
class _HomeState extends State<Home> {
#override
void initState() {
super.initState();
addData();
}
addData() async {
UserProvider _userProvider =
Provider.of<UserProvider>(context, listen: false);
await _userProvider.refreshUser();
}
#override
Widget build(BuildContext context) {
model.User? user = Provider.of<UserProvider>(context).getUser;
return Scaffold(
body: Center(
child: Text("this is homepage"),
),
);
}
}
In User_Provider.dart,
instead of doing:
User get getUser => _user!;
Do this:
User? get getUser => _user;

Permission Handler flutter multiple permissions error

Iam trying to add two permissions i.e. storage and camera. I have done the required setup in androidmanifest.xml file and in the main.dart called both the requests using switch. It gives the error but the app works and the permissions are also updated
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:teamup/Connectivity/network_binding.dart';
import 'package:teamup/Views/Login/sign_in.dart';
import 'package:teamup/Views/OnboardingScreen/onboarding_screen.dart';
import 'Views/OnboardingScreen/onboarding_constants.dart';
void main() async {
await GetStorage.init();
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Permission cameraPermission;
late Permission storagePermission;
PermissionStatus cameraPermissionStatus = PermissionStatus.denied;
PermissionStatus storagePermissionStatus = PermissionStatus.denied;
void _listenForPermission() async {
final cameraStatus = await Permission.camera.status;
final storageStatus = await Permission.storage.status;
setState(() {
cameraPermissionStatus = cameraStatus;
storagePermissionStatus = storageStatus;
});
switch (cameraStatus) {
case PermissionStatus.denied:
requestForPermission();
break;
case PermissionStatus.granted:
break;
case PermissionStatus.restricted:
Navigator.pop(context);
break;
case PermissionStatus.limited:
Navigator.pop(context);
break;
case PermissionStatus.permanentlyDenied:
Navigator.pop(context);
break;
}
switch (storageStatus) {
case PermissionStatus.denied:
requestForPermission();
break;
case PermissionStatus.granted:
break;
case PermissionStatus.restricted:
Navigator.pop(context);
break;
case PermissionStatus.limited:
Navigator.pop(context);
break;
case PermissionStatus.permanentlyDenied:
Navigator.pop(context);
break;
}
}
Future<void> requestForPermission() async {
final cameraStatus = await Permission.camera.request();
final storageStatus = await Permission.storage.request();
setState(() {
cameraPermissionStatus = cameraStatus;
storagePermissionStatus = storageStatus;
});
}
#override
void initState() {
super.initState();
_listenForPermission();
isViewed.writeIfNull('key', 0);
print(isViewed.read('key'));
}
#override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue, fontFamily: 'Glory'),
initialBinding: NetworkBinding() ,
home: isViewed.read('key') != 0
? const SignInPage()
: const OnboardingPage(),
);
}
}
This is the message that was displayed after installation
Launching lib\main.dart on Redmi Note 4 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
W/FlutterActivityAndFragmentDelegate(21677): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
Debug service listening on ws://127.0.0.1:56092/dh3Yn3XCkGg=/ws
Syncing files to device Redmi Note 4...
I/FA (21677): Tag Manager is not found and thus will not be used
I/flutter (21677): 0
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
[GETX] Instance "GetXNetworkManager" has been created
[GETX] Instance "GetXNetworkManager" has been initialized
I/Timeline(21677): Timeline: Activity_launch_request time:267480997 intent:Intent { act=android.content.pm.action.REQUEST_PERMISSIONS pkg=com.google.android.packageinstaller (has extras) }
E/flutter (21677): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(PermissionHandler.PermissionManager, A request for permissions is already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time)., null, null)
E/flutter (21677): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (21677): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677): #2 MethodChannelPermissionHandler.requestPermissions (package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart:71:9)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677): #3 PermissionActions.request (package:permission_handler/permission_handler.dart:44:31)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677): #4 _MyAppState.requestForPermission (package:teamup/main.dart:75:26)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677):
I/Timeline(21677): Timeline: Activity_launch_request time:267501469 intent:Intent { act=android.content.pm.action.REQUEST_PERMISSIONS pkg=com.google.android.packageinstaller (has extras) }
The switch-statements in _listenForPermission will call requestForPermission twice, if both cameraStatus and storageStatus have status PermissionStatus.denied. Therefore you get the exception:
PlatformException(PermissionHandler.PermissionManager, A request for permissions is already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time)., null, null)
The permission_handler package allows you to request multiple permission in one call like this:
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
].request();
print(statuses[Permission.location]);

Flutter/Dart - Unhandled Exception: MissingPluginException

I'm trying to access the device microphone on press with the aim of recording a voice-note. I have tried to access the current permission value but get the following error:
[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method checkPermissionStatus on channel flutter.baseflow.com/permissions/methods)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:159:7)
<asynchronous suspension>
#1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
#2 MethodChannelPermissionHandler.checkPermissionStatus (package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart:15:41)
#3 PermissionActions.status (package:permission_handler/permission_handler.dart:30:51)
#4 _InsideLeftState.build.<anonymous closure> (package:easy_tiger/screens/order_card_flow/insideleft.dart:19:62)
#5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#7 BaseTapGestureRecognizer._checkUp (pa<…>
[VERBOSE-2:profiler_metrics_ios.mm(184)] Error retrieving thread information: (ipc/send) invalid destination port
Here is the code for my screen:
import 'package:flutter/material.dart';
import 'package:audio_recorder/audio_recorder.dart';
import 'package:permission_handler/permission_handler.dart';
class InsideLeft extends StatefulWidget {
#override
_InsideLeftState createState() => _InsideLeftState();
}
class _InsideLeftState extends State<InsideLeft> {
#override
Widget build(BuildContext context) {
return Container(
child: GestureDetector(
child: Icon(Icons.mic),
onTap: () async {
PermissionStatus mic = await Permission.microphone.status;
print('microphone permission? ${mic.toString()}');
// try {
//// if (mic != PermissionStatus.granted) {
//// await Permission.microphone.request();
//// }
//// } catch (e) {
//// print(e);
//// }
},
),
);
}
}
Any thoughts how to get around this?
can you please try these things :
Migrate to androidX using android Studio
delete gradle caches
Good post about this topic: Flutter MissingPluginException with several plugins