Flutter - Unhandled Exception: Null check operator used on a null value - flutter

I am trying to initialize fields from a FirebaseFirestore document using GetXcontroller but I am getting the following error:
Unhandled Exception: Null check operator used on a null value.
The Controller gets created but it doesn't get initialized because of
the null check operator used on null value. Here's my code:
class DataController extends GetxController{
DocumentSnapshot? userDocument;
FirebaseAuth auth = FirebaseAuth.instance;
getUserProfileData() {
FirebaseFirestore.instance
.collection('users')
.doc(auth.currentUser!.uid) //Null check operator used on a null value
.snapshots()
.listen((event) {
userDocument = event;
});
}
#override
void onInit() {
super.onInit();
getUserProfileData();
}
}
My error log:
E/flutter (11591): #1 DataController.onInit
data_controller.dart:76
E/flutter (11591): #2 GetLifeCycleBase._onStart
lifecycle.dart:66
E/flutter (11591): #3 InternalFinalCallback.call
lifecycle.dart:12
E/flutter (11591): #4 GetInstance._startController
get_instance.dart:253
E/flutter (11591): #5 GetInstance._initDependencies
get_instance.dart:204
E/flutter (11591): #6 GetInstance.find
get_instance.dart:301
E/flutter (11591): #7 GetInstance.put
get_instance.dart:86
E/flutter (11591): #8 Inst.put
extension_instance.dart:89
E/flutter (11591): #9 main
main.dart:23
E/flutter (11591): <asynchronous suspension>
E/flutter (11591):

The error tells you that in this expression
auth.currentUser!.uid
the value of currentUser is null. This means that the user is not authenticated at that point. Make sure to perform user login before reaching this point of your code. As a safeguard you should also manually check if the user is authenticated before calling this chain. For example via
if (auth.currentUser != null) {
FirebaseFirestore.instance
.collection('users')
.doc(auth.currentUser!.uid) //Force unwrapping is now fine here
// ...
}

Related

Firebase Messaging requestPermission Unhandled Exception: [firebase_messaging/unknown] Attempt to invoke virtual method on a null object reference

I have a simple function to request Permission for Firebase Messaging
Future requestPermissionFCM() async {
final FirebaseMessaging messaging = FirebaseMessaging.instance;
final NotificationSettings settings = await messaging.requestPermission();
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permision');
} else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
print('User granted provisional permission');
} else {
print('user declined or has not accepted permission');
}
}
I call in during initState in main.dart
and exactly this line
final NotificationSettings settings = await messaging.requestPermission();
causes the Unhandled Exception
E/flutter (11771): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_messaging/unknown] Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
E/flutter (11771): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:653:7)
E/flutter (11771): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:315:18)
E/flutter (11771): <asynchronous suspension>
E/flutter (11771): #2 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:518:43)
E/flutter (11771): <asynchronous suspension>
E/flutter (11771): #3 MethodChannelFirebaseMessaging.requestPermission (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:271:36)
E/flutter (11771): <asynchronous suspension>
E/flutter (11771): #4 requestPermissionFCM (package:dev/services/fcm_services.dart:30:41)
E/flutter (11771): <asynchronous suspension>
Despite this exception, the app does not crush and messaging works as it should be including background push notifications. So what can it be?

Null Check operator used on a null value on flutter with Sqflite

I'm studying flutter with Sqflite and trying to make a small app, but I'm getting this error when I run the code, I've looked literaly everywhere to findout what it could be.
Here the code code who use the Sqflite package:
Future<Database> getDatabase() async {
final String path = join(await getDatabasesPath(), 'bytebank.db');
return openDatabase(path, onCreate: (db, version) {
db.execute('CREATE TABLE contacts'
'(id INTEGER PRIMARY KEY, '
'name TEXT, '
'account_number INTEGER)');
}, version: 1);
}
Future<int> save(Contact contact) async {
final Database db = await getDatabase();
final Map<String, dynamic> contactMap = Map();
contactMap['name'] = contact.name;
contactMap['account_number'] = contact.account;
contactMap['id'] = contact.id;
return db.insert('contacts', contactMap);
}
Future<List<Contact>> findAll() async {
final Database db = await getDatabase();
final List<Map<String, dynamic>> result = await db.query('contacts');
final List<Contact> contacts = [];
for (Map<String, dynamic> row in result) {
final Contact contact = Contact(
row['id'],
row['name'],
row['account_number'],
);
contacts.add(contact);
}
return contacts;
}
And here is the only one place where I use This functions:
void main() {
save(Contact('William', 2, 13456)).then((id) {
findAll().then((contacts) => print(contacts));
});
runApp(ByteBankApp());
}
Model Class:
class Contact {
final String name;
final int account;
final int id;
Contact( this.id,
this.name,
this.account,
);
#override
String toString() {
return 'Contact{name: $name, account: $account}';
}
}
Error Trace back:
Launching lib\main.dart on sdk gphone x86 arm in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Debug service listening on ws://127.0.0.1:52296/07rtnvW9tlQ=/ws
Syncing files to device sdk gphone x86 arm...
E/flutter (28649): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
E/flutter (28649): #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
E/flutter (28649): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
E/flutter (28649): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
E/flutter (28649): #3 invokeMethod (package:sqflite/src/sqflite_impl.dart:17:13)
E/flutter (28649): #4 SqfliteDatabaseFactoryImpl.invokeMethod (package:sqflite/src/factory_impl.dart:82:7)
E/flutter (28649): #5 SqfliteDatabaseFactoryMixin.safeInvokeMethod.<anonymous closure> (package:sqflite_common/src/factory_mixin.dart:41:38)
E/flutter (28649): #6 wrapDatabaseException (package:sqflite/src/exception_impl.dart:7:32)
E/flutter (28649): #7 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:78:7)
E/flutter (28649): #8 SqfliteDatabaseFactoryMixin.safeInvokeMethod (package:sqflite_common/src/factory_mixin.dart:41:7)
E/flutter (28649): #9 SqfliteDatabaseFactoryMixin.getDatabasesPath (package:sqflite_common/src/factory_mixin.dart:153:26)
E/flutter (28649): #10 getDatabasesPath (package:sqflite/sqflite.dart:161:54)
E/flutter (28649): #11 getDatabase (package:bytebank/database/app_database.dart:6:34)
E/flutter (28649): #12 save (package:bytebank/database/app_database.dart:16:29)
E/flutter (28649): #13 main (package:bytebank/main.dart:7:3)
E/flutter (28649): #14 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (28649): #15 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (28649): #16 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (28649): #17 _runZoned (dart:async/zone.dart:1789:10)
E/flutter (28649): #18 runZonedGuarded (dart:async/zone.dart:1777:12)
E/flutter (28649): #19 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:138:5)
E/flutter (28649): #20 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (28649): #21 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (28649):
I am not sure if will help, but I was running into a similar issue when initializing a database in an async "main" method. Adding the following:
WidgetsFlutterBinding.ensureInitialized();
inside the method before the code initializing the database solved the problem.

Unhandled Exception: NoSuchMethodError: The method 'call' was called on null

I upgraded the flutter sdk by flutter upgrade --force. The project was working fine before upgrade but I am getting error after upgrade. I am currently working in lastest stable version of flutter.
E/flutter (17687): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The method 'call' was called on null.
E/flutter (17687): Receiver: null
E/flutter (17687): Tried calling: call()
E/flutter (17687): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (17687): #1 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:31:24)
E/flutter (17687): #2 SembastDatabase.flush (package:sembast/src/database_impl.dart:593:27)
E/flutter (17687): #3 SembastDatabase.open (package:sembast/src/database_impl.dart:879:11)
E/flutter (17687): <asynchronous suspension>
E/flutter (17687): #4 DatabaseOpenHelper.openDatabase.<anonymous closure> (package:sembast/src/database_factory_mixin.dart:80:7)
E/flutter (17687): <asynchronous suspension>
E/flutter (17687): #5 BasicLock.synchronized (package:synchronized/src/basic_lock.dart:33:16)
E/flutter (17687): <asynchronous suspension>
E/flutter (17687): #6 DaoDatabase._openDatabase (package:kitabyatra/db/DaoDatabase.dart:43:26)
E/flutter (17687): <asynchronous suspension>
I have implemented as follows:
class DaoDatabase {
DaoDatabase();
static final DaoDatabase _singleton = DaoDatabase();
static DaoDatabase get instance => _singleton;
Completer<Database> _dbOpenCompleter;
Future<Database> get database async {
if (_dbOpenCompleter == null) {
_dbOpenCompleter = Completer<Database>();
_openDatabase();
}
return _dbOpenCompleter.future;
}
Future<dynamic> _openDatabase() async {
final Directory appDocumentDir = await getApplicationDocumentsDirectory();
final String dbPath = join(appDocumentDir.path, Strings.appDbName);
final Database database = await databaseFactoryIo.openDatabase(dbPath); //--> Getting error here
_dbOpenCompleter.complete(database);
}
}

How to log out user and How to check user verify mail

I got the following problem.
When user register he will be on a page, where I show a message like check your Email account. And when user check his account and confirm his mail he automatically get to homepage. So far so good. But when user press register button an get mail and reload the page he get also inside homepage without confirm his mail.
I trie this
Future<String> signIN(String email, String password) async {
try {
UserCredential result =await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email.trim(),
password: password,
);
User user = result.user;
if(user.emailVerified){
return user.uid;
}
} on FirebaseAuthException catch (e) {
but not working.
here's my verify email page
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:projectandroidstudiodenya/seitenleiste/homepage.dart';
class VerifyScreen extends StatefulWidget {
#override
_VerifyScreenState createState() => _VerifyScreenState();
}
class _VerifyScreenState extends State<VerifyScreen> {
final auth= FirebaseAuth.instance;
User user;
Timer timer;
#override
void initState() {
user= auth.currentUser;
user.sendEmailVerification();
timer= Timer.periodic(Duration(seconds: 5), (timer) {
checkEmailverifyed();
});
super.initState();
}
#override
void dispose() {
timer.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body:Center(
)
);
}
Future<void> checkEmailverifyed() async{
user=auth.currentUser;
await user.reload();
if(user.emailVerified){
timer.cancel();
Navigator.of(context).
pushReplacement(MaterialPageRoute(builder:(context)=> Homepage()));
}
}
}
Maybe anyone can help.
And also when user press logout button nothing happened. but when user restart the app he logged out.
here's my logout pressed method:
onPressed: () {
FirebaseAuth.instance.signOut();
FirebaseAuth.instance.signOut();Navigator.pushNamedAndRemoveUntil(context, LoginScreen.route, (route) => false);
Heres the error of the sign out:
D/FirebaseAuth(26776): Notifying id token listeners about a sign-out event.
D/FirebaseAuth(26776): Notifying auth state listeners about a sign-out event.
E/flutter (26776): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Could not find a generator for route RouteSettings("SignIn", null) in the _WidgetsAppState.
E/flutter (26776): Make sure your root app widget has provided a way to generate
E/flutter (26776): this route.
E/flutter (26776): Generators for routes are searched for in the following order:
E/flutter (26776): 1. For the "/" route, the "home" property, if non-null, is used.
E/flutter (26776): 2. Otherwise, the "routes" table is used, if it has an entry for the route.
E/flutter (26776): 3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
E/flutter (26776): 4. Finally if all else fails onUnknownRoute is called.
E/flutter (26776): Unfortunately, onUnknownRoute was not set.
E/flutter (26776): #0 _WidgetsAppState._onUnknownRoute.<anonymous closure> (package:flutter/src/widgets/app.dart:1219:9)
E/flutter (26776): #1 _WidgetsAppState._onUnknownRoute (package:flutter/src/widgets/app.dart:1234:6)
E/flutter (26776): #2 NavigatorState._routeNamed (package:flutter/src/widgets/navigator.dart:4148:37)
E/flutter (26776): #3 NavigatorState.pushNamedAndRemoveUntil (package:flutter/src/widgets/navigator.dart:4391:34)
E/flutter (26776): #4 Navigator.pushNamedAndRemoveUntil (package:flutter/src/widgets/navigator.dart:2042:34)
E/flutter (26776): #5 _openSignOutDrawer.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:projectandroidstudiodenya/seitenleiste/seitenleiste.dart:188:90)
E/flutter (26776): #6 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (26776): #7 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (26776): <asynchronous suspension>
E/flutter (26776):
And the error of the sig in:
E/flutter (26776): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: The getter 'emailVerified' was called on null.
E/flutter (26776): Receiver: null
E/flutter (26776): Tried calling: emailVerified
E/flutter (26776): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (26776): #1 AuthService.signIN (package:projectandroidstudiodenya/services/auth.dart:44:44)
E/flutter (26776): #2 _LoginScreenState._buildLoginBtn.<anonymous closure> (package:projectandroidstudiodenya/authenticate/signin.dart:170:48)
E/flutter (26776): #3 _LoginScreenState._buildLoginBtn.<anonymous closure> (package:projectandroidstudiodenya/authenticate/signin.dart:168:24)
E/flutter (26776): #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:994:20)
E/flutter (26776): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (26776): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:607:11)
E/flutter (26776): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:296:5)
E/flutter (26776): #8 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:267:7)
E/flutter (26776): #9 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter (26776): #10 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:443:20)
E/flutter (26776): #11 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:419:22)
E/flutter (26776): #12 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:288:11)
E/flutter (26776): #13 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:374:7)
E/flutter (26776): #14 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:338:5)
E/flutter (26776): #15 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:296:7)
E/flutter (26776): #16 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:279:7)
E/flutter (26776): #17 _rootRunUnary (dart:async/zone.dart:1370:13)
E/flutter (26776): #18 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (26776): #19 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
E/flutter (26776): #20 _invoke1 (dart:ui/hooks.dart:186:10)
E/flutter (26776): #21 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:282:7)
E/flutter (26776): #22 _dispatchPointerDataPacket (dart:ui/hooks.dart:96:31)
E/flutter (26776):
My sig in method looks like that:
Future<String> signIN(String email, String password) async {
try {
if(FirebaseAuth.instance.currentUser.emailVerified) {
( await _auth.signInWithEmailAndPassword(
email: email.trim(), password: password,)).user;
// User user = result.user;
}
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
}
}
return null;
}
It looks different because I changed it like it was before that so I can check if maybe it was on the changes it do because it runs at this point.
You should check email verification within you're sign-in method, and if the email was verified then return instance.signInWithEmailAndPassword.
full code:
Future<String> signIN(String email, String password) async {
try {
if(FirebaseAuth.instance.currentUser.emailVerified) {
( await _auth.signInWithEmailAndPassword(
email: email.trim(), password: password,)).user;
return "success";
// User user = result.user;
}
} on FirebaseAuthException catch (e) {
switch (e.code) {
case 'invalid-email':
{
return 'Email is not valid';
}
case 'user-disabled':
{
return 'Account is not active';
}
case 'user-not-found':
{
return 'No user found';
}
case 'wrong-password':
{
return 'wrong password';
}
default:
{
return 'Unexpected error!';
}
}
}
return return "error";;
}
so every moment when signIN calling it would check email verification and if it verified it would work if it isn't it will return "error" or other problem variants, and you can listen to response so when it gives you an error you should return a snackBar, if it returns "success" then you would navigate.
Solution of logout issue:
onPressed: () {
FirebaseAuth.instance.signOut().then((){
Navigator.pushNamedAndRemoveUntil(context, LoginScreen.route (route) => false);
});

Flutter Api call Unhandled Exception

i have a problem with api call,
in the project i have another call and it work, this call doesn't work in any way
// file meteo.dart
class Meteo {
int id;
double temperatura;
String name;
Meteo(this.id, this.temperatura, this.name);
Meteo.fromMap(Map<String, dynamic> mappa){
this.id = mappa['id'];
this.temperatura = mappa['main']['temp'];
this.name = mappa['name'].toString();
}
}
This is the model of the response
Future ferentinoGet() async {
var dio = Dio();
Response response = await
dio.get('https://api.openweathermap.org/data/2.5/weather?q=ferentino&appid=****************');
final resJson = response.data;
datiFerentino = resJson
.map<Meteo>((mappa) => Meteo.fromMap(mappa))
.toList();
print(response.data);
}
This is the api call
[VERBOSE-2:ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'map' with matching arguments.
Receiver: _LinkedHashMap len:13
Tried calling: map<Meteo>(Closure: (dynamic) => Meteo)
Found: map<K2, V2>((K, V) => MapEntry<K2, V2>) => Map<K2, V2>
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _HomeScreenState.ferentinoGet (package:ferentino/main.dart:223:10)
<asynchronous suspension>
#2 _HomeScreenState.initState (package:ferentino/main.dart:43:5)
#3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4765:58)
#4 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4601:5)
#5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3569:14)
#6 Element.updateChild (package:flutter/src/widgets/framework.dart:3327:18)
#7 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:6118:14)
#8 Element.<…>
this is the error.
Can you help me?
Thank you
I think you process your JSON response as a List but it looks resJson is a Map. But map method for Map has different prototype.