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
// ...
}
I need help.
I'm trying to extract files from an archive.
var byteData = await rootBundle.load('assets/res.zip');
var buffer = byteData.buffer;
var archive = ZipDecoder().decodeBytes(buffer.asUint8List(),
verify: true, password: '123');
for (final file in archive) {
final filename = file.name;
if (file.isFile) {
final data = file.content as List<int>;
File('$tempPath/files/$filename')
..createSync(recursive: true)
..writeAsBytesSync(data);
} else {
Directory('$tempPath/files/$filename').create(recursive: true);
}
}
But I'm getting this error..................
E/flutter ( 8813): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unsupported operation: Cannot modify an unmodifiable list
E/flutter ( 8813): #0 _UnmodifiableUint8ArrayView.[]= (dart:typed_data-patch/typed_data_patch.dart:5391:5)
E/flutter ( 8813): #1 ZipFile._decodeZipCrypto (package:archive/src/zip/zip_file.dart:192:12)
E/flutter ( 8813): #2 ZipFile.content (package:archive/src/zip/zip_file.dart:129:27)
E/flutter ( 8813): #3 ZipDecoder.decodeBuffer (package:archive/src/zip_decoder.dart:32:41)
E/flutter ( 8813): #4 ZipDecoder.decodeBytes (package:archive/src/zip_decoder.dart:16:12)
E/flutter ( 8813): #5 _HomePageState.dataWriteToLocal (package:mytest/Pages/home_page.dart:417:36)
E/flutter ( 8813): <asynchronous suspension>
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?
im using this package image_downloader 0.31.0 i already look for the example to use this but i always got this error, don't know why
error results
E/flutter (28894): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: MissingPluginException(No implementation found for method downloadImage on channel plugins.ko2ic.com/image_downloader)
E/flutter (28894): #0 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:165
E/flutter (28894): <asynchronous suspension>
E/flutter (28894): #1 ImageDownloader.downloadImage (package:image_downloader/image_downloader.dart:31:12)
E/flutter (28894): <asynchronous suspension>
E/flutter (28894): #2 _SurveyTicketState.openQrLink
package:onesmile/…/survey/survey_ticket.dart:45
E/flutter (28894): <asynchronous suspension>
E/flutter (28894):
this is my code
downloadImage() async {
var url = 'https://images.unsplash.com/photo-1644982647970-e72b0397e57b?ixlib=rb-1.2.1&raw_url=true&q=80&fm=jpg&crop=entropy&cs=tinysrgb&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=435';
try {
var imageId = await ImageDownloader.downloadImage(url);
if (imageId == null) {
return;
}
var path = await ImageDownloader.findPath(imageId);
} on PlatformException catch (error) {
print('======== $error');
}
}
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.