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

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;

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> {

dart/flutter:: type 'Null' is not a subtype of type 'String' in type cast ERRor, not able to fetch data

I am running into a "type 'Null' is not a subtype of type 'String' in type cast" when I try to retrieve the data.
not sure what the issue is... I think the data is not being found or something along those lines
source code:: https://github.com/casas1010/flutter_firebase_vendor_management
error message::
════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building JobApplicationsListView(dirty):
type 'Null' is not a subtype of type 'String' in type cast
The relevant error-causing widget was
JobApplicationsListView
lib/…/job_applications/job_application_view.dart:75
When the exception was thrown, this was the stack
#0 new CloudJobApplication.fromSnapshot
package:ijob_clone_app/…/cloud/cloud_job_application.dart:27
#1 FirebaseCloudStorage.allJobApplications.<anonymous closure>.<anonymous closure>
package:ijob_clone_app/…/cloud/firebase_cloud_storage.dart:49
#2 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#3 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#4 WhereIterator.moveNext (dart:_internal/iterable.dart:438:22)
#5 Iterable.length (dart:core/iterable.dart:497:15)
#6 JobApplicationsListView.build
package:ijob_clone_app/…/widgets/job_application_list_widget.dart:27
#7 StatelessElement.build
package:flutter/…/widgets/framework.dart:4949
#8 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4878
#9 Element.rebuild
package:flutter/…/widgets/framework.dart:4604
#10 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4859
#11 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4853
#12 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3863
#13 Element.updateChild
package:flutter/…/widgets/framework.dart:3586
#14 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4904
#15 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:5050
#16 Element.rebuild
package:flutter/…/widgets/framework.dart:4604
#17 BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2667
#18 WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:882
#19 RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:378
#20 SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1175
#21 SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1104
#22 SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:1015
#23 _invoke (dart:ui/hooks.dart:148:13)
#24 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:318:5)
#25 _drawFrame (dart:ui/hooks.dart:115:31)
════════════════════════════════════════════════════════════════════════════════
D/TrafficStats( 9769): tagSocket(99) with statsTag=0xffffffff, statsUid=-1
CloudJobApplication::
#immutable
class CloudJobApplication {
final String documentId;
final String jobApplicatorId;
final String jobApplicationState;
final String jobApplicationSubState;
const CloudJobApplication({
required this.documentId,
required this.jobApplicatorId,
required this.jobApplicationState,
required this.jobApplicationSubState,
});
// acts as constructor
CloudJobApplication.fromSnapshot(
QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
jobApplicatorId = snapshot.data()[jobApplicatorIdColumn] as String,
jobApplicationState =
snapshot.data()[jobApplicationStateColumn] as String,
jobApplicationSubState =
snapshot.data()[jobApplicationSubStateColumn] as String;
}
FirebaseCloudStorage::
class FirebaseCloudStorage {
final job = FirebaseFirestore.instance.collection('jobs');
final jobApplication =
FirebaseFirestore.instance.collection('job applications');
// This works perfect for getting the jobs
Stream<Iterable<CloudJob>> allJobs({required String jobCreatorId}) =>
job.snapshots().map((event) => event.docs
.map((doc) => CloudJob.fromSnapshot(doc))
.where((job) => job.jobCreatorId == jobCreatorId));
// this does not work. i copied the code from above and changed it
Stream<Iterable<CloudJobApplication>> allJobApplications() =>
jobApplication.snapshots().map((event) => event.docs
.map((doc) => CloudJobApplication.fromSnapshot(doc))
.where((jobApplication) =>
jobApplication.documentId == 'f2FvzZmr51v1wyrYZYoM'));
// singleton
static final FirebaseCloudStorage _shared =
FirebaseCloudStorage._sharedInstance();
FirebaseCloudStorage._sharedInstance();
factory FirebaseCloudStorage() => _shared;
}
JobApplicationsView:: ( this is where the issue starts, the issue appears when this widget tries to retrieve the data from the server i thin )
import 'package:flutter/material.dart';
import '../../services/cloud/cloud_job_application.dart';
import '../../utilities/widgets/job_application_list_widget.dart';
import '../../utilities/widgets/jobs_list_widget.dart';
import '/constants/routes.dart';
import '/enums/menu_action.dart';
import '/services/auth/auth_service.dart';
import '/services/cloud/cloud_job.dart';
import '/services/cloud/firebase_cloud_storage.dart';
import '/utilities/dialogs/logout_dialog.dart';
class JobApplicationsView extends StatefulWidget {
const JobApplicationsView({Key? key}) : super(key: key);
#override
_JobApplicationsViewState createState() => _JobApplicationsViewState();
}
class _JobApplicationsViewState extends State<JobApplicationsView> {
late final FirebaseCloudStorage _jobsService;
String get userId => AuthService.firebase().currentUser!.id;
#override
void initState() {
_jobsService = FirebaseCloudStorage();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Your job applications'),
actions: [
IconButton(
onPressed: () {
// Navigator.of(context).pushNamed(createOrUpdateJobRoute);
},
icon: const Icon(Icons.add),
),
PopupMenuButton<MenuAction>(
onSelected: (value) async {
prin('code removed')
},
itemBuilder: (context) {
return const [
PopupMenuItem<MenuAction>(
value: MenuAction.logout,
child: Text('Log out'),
),
];
},
)
],
),
body: StreamBuilder(
stream: _jobsService.allJobApplications(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.active:
if (snapshot.hasData) {
final allJobs = snapshot.data as Iterable<CloudJobApplication>;
print(snapshot);
return JobApplicationsListView( // ERROR IS OCURRING HERE
jobs: allJobs,
);
return Text('results');
} else {
return const CircularProgressIndicator();
}
default:
return const CircularProgressIndicator();
}
},
),
);
}
}
Try like this
CloudJobApplication.fromSnapshot(
QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
jobApplicatorId = snapshot.data()[jobApplicatorIdColumn] ?? "",
jobApplicationState = snapshot.get(jobApplicationStateColumn) ?? "",
jobApplicationSubState =
snapshot.get(jobApplicationSubStateColumn) ?? "";

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

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

Failed assertion: line 1233 pos 12: 'renderObject.child == child': is not true

I have created a provider where I have created a future to get user id from SharedPreferences.
I have created my provider like below
class UserInfoProvider with ChangeNotifier{
late int _userId;
get userID {
return _userId;
}
Future getAndSetUserId() async
{
final prefs = await SharedPreferences.getInstance();
final userEnt = json.decode(prefs.getString('userEnt') ?? '{}');
_userId = userEnt['userId'];
}
}
I have a screen called SilverCommonAppBar, Where I have tried to get this user Id like below
class SilverCommonAppBar extends StatefulWidget {
const SilverCommonAppBar({
Key? key,
}) : super(key: key);
#override
State<SilverCommonAppBar> createState() => SilverCommonAppBarState();
}
class SilverCommonAppBarState extends State<SilverCommonAppBar> {
late int userId;
bool _isInit = true;
#override
void initState() {
super.initState();
}
#override
void didChangeDependencies() {
if(_isInit)
{
Provider.of<UserInfoProvider>(context).getAndSetUserId();
}
_isInit = false;
super.didChangeDependencies();
}
#override
Widget build(BuildContext context) {
userId = Provider.of<UserInfoProvider>(context).userID;
print(Provider.of<UserInfoProvider>(context).userID);
return Container();
}
}
I'm getting error : Failed assertion: line 1233 pos 12: 'renderObject.child == child': is not true.
Error details :
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY
╞═══════════════════════════════════════════════════════════
The following assertion was thrown building Consumer<AuthProvider>(dependencies:
[_InheritedProviderScope<AuthProvider?>]):
'package:flutter/src/widgets/binding.dart': Failed assertion: line 1233 pos 12:
'renderObject.child
== child': is not true.
Either the assertion indicates an error in the framework itself, or we should provide
substantially
more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md
The relevant error-causing widget was:
Consumer<AuthProvider>
Consumer:file:///Users/alimonkarim/Desktop/project/miles_design_flutter/lib/main.dart:50:10
When the exception was thrown, this was the stack:
#2 RenderObjectToWidgetElement.removeRenderObjectChild
(package:flutter/src/widgets/binding.dart:1233:12)
#3 RenderObjectElement.detachRenderObject
(package:flutter/src/widgets/framework.dart:6005:37)
#4 Element.deactivateChild (package:flutter/src/widgets/framework.dart:3857:11)
#5 Element.updateChild (package:flutter/src/widgets/framework.dart:3540:9)
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4832:16)
#7 Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#8 StatelessElement.update (package:flutter/src/widgets/framework.dart:4883:5)
#9 Element.updateChild (package:flutter/src/widgets/framework.dart:3530:15)
#10 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4832:16)
#11 Element.rebuild (package:flutter/src/widgets/framework.dart:4529:5)
#12 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#13 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:891:21)
#14 RendererBinding._handlePersistentFrameCallback
(package:flutter/src/rendering/binding.dart:370:5)
#15 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1146:15)
#16 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1083:9)
#17 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure>
(package:flutter/src/scheduler/binding.dart:864:7)
(elided 6 frames from class _AssertionError, class _RawReceivePortImpl, class _Timer, and
dart:async-patch)
══════════════════════════════════════════════════════════════════════════════════════════════════
══
If I make userId static , that means If I remove late and set user id with 88
int userId = 88;
And if I remove below lines , it's working fine
userId = Provider.of<UserInfoProvider>(context).userID;
print(Provider.of<UserInfoProvider>(context).userID);
Why I'm not able to set userId from provider to late userId ?

Screen not loading after login is authenticated in flutter

I have created a route to the home screen which should be displayed after login is successful. However, my circular bar just keeps moving (indicating isLoading stage) and the home screen does not show up in the simulator.
I am aware that the login is successful since my response variable does print the information in the console that it accesses after login.
On pressing the login the button 2 main issues are displayed:
1) Exception thrown while handling a gesture
2) Unhandled Exception: Failed assertion: boolean expression must not be null
I am unable to solve this these 2 issues. Any help would be great.
Thanks in advance!
There is no compilation error. The following are the main issues shown after pressing the login button (complete stack tree and message posted later in the question):
flutter: The following ArgumentError was thrown while handling a gesture:
flutter: Invalid argument (onError): Error handler must accept one Object or one Object and a StackTrace as
flutter: arguments, and return a a valid result: Closure: (Exception) => void
Unhandled Exception: Failed assertion: boolean expression must not be null
The console message posted later refers to 3 files. I have posted important code of the files below.
File: login_screen.dart
import 'dart:ui';
import 'package:flutter/material.dart';
class LoginScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new LoginScreenState();
}
}
class LoginScreenState extends State<LoginScreen>
implements LoginScreenContract, AuthStateListener {
BuildContext _ctx;
bool _isLoading = false;
final formKey = new GlobalKey<FormState>();
final scaffoldKey = new GlobalKey<ScaffoldState>();
String _password, _username;
LoginScreenPresenter _presenter;
LoginScreenState() {
_presenter = new LoginScreenPresenter(this);
var authStateProvider = new AuthStateProvider();
authStateProvider.subscribe(this);
}
void _submit() {
final form = formKey.currentState;
if (form.validate()) {
setState(() => _isLoading = true);
form.save();
_presenter.doLogin(_username, _password);
}
}
void _showSnackBar(String text) {
scaffoldKey.currentState
.showSnackBar(new SnackBar(content: new Text(text)));
}
#override
onAuthStateChanged(AuthState state) {
if(state == AuthState.LOGGED_IN)
Navigator.of(_ctx).pushReplacementNamed("/home");
}
#override
Widget build(BuildContext context) {
_ctx = context;
....(UI for login screen)
#override
void onLoginError(String errorTxt) {
_showSnackBar(errorTxt);
setState(() => _isLoading = false);
}
#override
void onLoginSuccess(User user) async {
HomeScreen()));
_showSnackBar(user.toString());
setState(() => _isLoading = false);
var db = new DatabaseHelper();
await db.saveUser(user);
var authStateProvider = new AuthStateProvider();
HomeScreen()));
authStateProvider.notify(AuthState.LOGGED_IN);
onAuthStateChanged(AuthState.LOGGED_IN);
}
}
File: login_screen_presenter.dart
import 'package:better_login/rest_ds.dart';
import 'package:better_login/user.dart';
abstract class LoginScreenContract {
void onLoginSuccess(User user);
void onLoginError(String errorTxt);
}
class LoginScreenPresenter {
LoginScreenContract _view;
RestDatasource api = new RestDatasource();
LoginScreenPresenter(this._view);
doLogin(String username, String password) {
api.login(username, password).then((User user) {
_view.onLoginSuccess(user);
}).catchError((Exception error) =>
_view.onLoginError(error.toString()));
}
}
File: rest_ds.dart
static final LOGIN_URL = "https://legacy- api.example.com/v1/auth/login";
Future<User> login(String username, String password) {
return _netUtil.post(LOGIN_URL, body: {
"username": username,
"password": password
}).then((dynamic res) {
print(res.toString());
if(res["error"]){ throw new Exception(res["error_msg"]);}
return new User.map(res["user"]);
});
}
}
This is the complete info displayed in the console:
flutter: The following ArgumentError was thrown while handling a gesture:
flutter: Invalid argument (onError): Error handler must accept one Object or one Object and a StackTrace as
flutter: arguments, and return a a valid result: Closure: (Exception) => void
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #2 LoginScreenPresenter.doLogin (package:better_login/login_screen_presenter.dart:17:8)
flutter: #3 LoginScreenState._submit (package:better_login/login_screen.dart:41:18)
flutter: #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14)
flutter: #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30)
flutter: #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
flutter: #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9)
flutter: #8 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:177:9)
flutter: #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:436:9)
flutter: #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
flutter: #11 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
flutter: #12 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:221:19)
flutter: #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22)
flutter: #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
flutter: #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
flutter: #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
flutter: #20 _invoke1 (dart:ui/hooks.dart:233:10)
flutter: #21 _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)
flutter: (elided 5 frames from package dart:async)
flutter:
flutter: Handler: onTap
flutter: Recognizer:
flutter: TapGestureRecognizer#398b8(debugOwner: GestureDetector, state: possible, won arena, finalPosition:
flutter: Offset(194.0, 504.0), sent tap down)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: {status: success, message: Authentication Success, executionTime: 0.052, data: {token: U2FsdGVkX19ZQS5wQXRYWTkh2o4PyrtmhS4kELJO0WsEBDbn30G9Oig/13fzHzqZ, custKey: anb2mNXFERnJ4IQW....(rest is info got on login)
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Failed assertion: boolean expression must not be null
#0 RestDatasource.login.<anonymous closure> (package:better_login/rest_ds.dart:21:13)
#1 _rootRunUnary (dart:async/zone.dart:1132:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#3 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#5 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#6 Future._complete (dart:async/future_impl.dart:473:7)
#7 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#8 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28:18)
#9 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294:13)
#10 _withClient (package:http/http.dart)
<asynchronous suspension>
#11 post (package:http/http.dart:69:5)
#12 NetworkUtil.post (package:better_login/network_util.dart<…>
There are several issues in your code:
catchError param is not of type Exception is of type Object. You can use the second param of catchError, test to filter errors received. This is the cause of the crash report trace The following ArgumentError was thrown while handling a gestur.
the main cause of the crash is here if(res["error"]){ throw new Exception(res["error_msg"]);}, because the res["error"] is probably null. To fix it change it to if(res["error"] != null) .....
Refactoring points:
you don't need to save the build context in a _ctx variable, any subclass of State has access to it's main context via context property.