The method 'add' was called on null : Flutter, SQFlite - flutter

I am getting data from SQLite in flutter. When I try to convert the list of Map to list of Objects. It gives the error of
The method 'add' was called on null
On debuging, it shows that it has data but still gives the error.
Here is my code
List<Image> imagesList;
if (imagesListMap != null) {
imagesListMap.forEach((element) {
imagesList.add(Image.FromDatabase(element));
});
}
And its the debugging screenshot

You need to initialize the List like this before calling add() on it..
List<Image> imagesList = [];

Related

forEach not working in my map iteration. Any experts here?

I'm working with an app in Flutter that writes data to a Firebase database that I created and then reads and displays it in a list view in my app. Currently the app writes the data correctly and also reads it and prints it to the command line. However, when I code the bit that's supposed to then take that data and dump it into a list that can be printed in list view I get the following error when trying to iterate it from a map to a list using a forEach command. The error is "The method 'forEach' can't be unconditionally invoked because the receiver can be 'null'."
I've even tried adding '!' to force it to run since I know it's not null but it still won't work. Any ideas? The code for that section is below. Thanks in advance!
_ListViewReadPageState() {
// load all students from firebase database and display them in list view
FirebaseDatabase.instance.ref("students").once()
.then((databaseEvent) {
print("Successfully loaded the data");
print(databaseEvent);
print("Key:");
print(databaseEvent.snapshot.key);
print("value:");
print(databaseEvent.snapshot.value);
print("Iterating the value map");
var studentTmpList = [];
databaseEvent.snapshot.value.forEach((k, v) {
print(k);
print(v);
studentTmpList.add(v);
});
print("Final student list");
print(studentTmpList);
studentList = studentTmpList;
setState(() {
});
}).catchError((error) {
print("Failed to load the data");
print(error);
});
}
I've tried adding '!' to force the code to run since I know the data isn't null but no dice. When I try adding the '!' I get a new error stating "The method 'forEach' isn't defined for the type 'Object'".

[ERROR:flutter/runtime/dart_vm_initializer.cc(41) Unhandled Exception: Null check operator used on a null value

I am unable to store data in the excel sheet because of this error. Even though the data is getting stored in the variable.
I changed !. to ?. in the insert function, then I was able to move forward but the data was not getting stored in the excel sheet.
Map<String, dynamic> data = {
DataSet.imagePath: viewImage,
DataSet.option11: opt11,
DataSet.option12: opt12,
DataSet.option13: opt13,
DataSet.option14: opt14,
DataSet.option21: opt21,
DataSet.option22: opt22,
DataSet.option23: opt23,
DataSet.option24: opt24,
};
await DataSheetApi.insert([data]);
This is where I am adding storing data to the variable data.
static Future insert(List<Map<String, dynamic>> rowList) async {
dataSheet!.values.map.appendRows(rowList);
}
This is where the error is.
Screenshot of the error.
Try to check null and then procced,
static Future insert(List<Map<String, dynamic>> rowList) async {
if(dataSheet!=null) dataSheet.values.map.appendRows(rowList);
else log("got null"); //from `dart.developer`
}

Error in checking the existence of a sublist in a list from firebase

I want to check if all elements in a sublist exist in a list so I created this extension:
extension StringExtension on List<dynamic> {
bool containsAll(List<dynamic> sublist) {
for (var element in sublist) {
if (!this.contains(element)) {
return false;
}
}
return true;
}
}
But when I run it like this :
documments[index]['Read'].containsAll(group.members)
Read is a list of string in firebase cloud
It gives me this error:
Class 'List<dynamic>' has no instance method 'containsAll'.
Receiver: Instance(length:1) of '_GrowableList'
Tried calling: containsAll(Instance(length:3) of '_GrowableList')
This is how the code appears in the VSC, it looks like the function isn't detected by the VSC :
I don't know exactly where's the problem, but I reverse the comparison and it works just fine now
For :
documments[index]['Read'].containsAll(group.members)
to
group.members.containsAllBack(documments[index]['Read'])

How to read data from cloud firestore with firebase function and loop and push it to list

I am trying to read data from firestore collection to get notification token and push it to a list and pass the list to SendtoDevice function to send push notification.
I am facing issue when using foreach function and push the data getting error "for each is not a valid function"
let tokenList = [];
const userNotificationTokenDocs = await db.collection("userToken").doc(userId).get()
.then(querySnapshot => {
querySnapshot.forEach((doc) => {
console.log(doc.data().Tokens);
tokenList.push(doc.data().Tokens);
});
return null;
});
**other option which i tried, with same error.**
userNotificationTokenDocs.forEach(function(docs){
console.log(docs.data());
if(docs.data() != null){
tokenList.push(docs.data().Token);
}
});
Please help me, I am stuck with this.
found some BASIC mistake in your coding.
const userNotificationTokenDocs will always null , because you return null. forEach is void function.
Using await and then is unecessery. choose 1.
=> arrow is a shorthand for { return expr; } .
if you only have 1 expresion, you can shorthand with arrow. but if you have morethan 1 expression, just use bracket {} . documentation
userNotificationTokenDocs.forEach(function(docs){ this will error since null value cant use forEach.
I think your IDE should give you alert there's an error in your code. but you choose to run it instead fixing the error.
but is ok, keep learning code. :)

The method was called on null error flutter Hive

Opening the box
var savedList;
Future initiateHive() async {
///Creating a HiveBox to Store data
savedList = await Hive.openBox('Musicbox');
}
The function to put data to hive
var songFav = SongPlayList()..songInfo = songs[currentIndex].id;
print(songs[currentIndex].id);
savedList.put(songs[currentIndex].id, songFav);
The error is
Another exception was thrown: NoSuchMethodError: The method 'put' was
called on null.
I think the problem is that savedList.put(songs[currentIndex].id, songFav); is called before initiateHive() finishes execution since initiateHive() is asynchronous so savedList is still null
you can do something like:
if (savedList != null){
savedList.put(songs[currentIndex].id, songFav);
}