The method was called on null error flutter Hive - flutter

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);
}

Related

[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`
}

My firebase callable cloud function is called twice (when I called only once), how can I avoid my flutter app from failure?

I am trying to make a callable function in firebase, but when I call it from my flutter app it is called twice.
The Issue is, I am calling the function while sending some parameters to perform on by cloud function.
The automatic second call initiates with null parameter, which causes chaos because the function return empty list.
Here is my function code.
callable function
exports.getItem = functions.https.onCall(async (data, context) => {
// Data NULL Check
if (data == null) {
console.log("NULL DATA RECIEVED");
console.log(`null event id ${context.eventID}`);
} else {
console.log(`event id ${context.eventID}`);
const itemList = [];
console.log("Begin...............");
console.log(data);
console.log(data["closet"]);
console.log(data["from"].toString());
console.log(data["count"].toString());
const querySnapshot = await admin.firestore().collection("t_shirt").get();
querySnapshot.doc.forEach((doc)=>{
itemList.push(doc);
});
console.log(itemList.length);
if (itemList.length > 0) {
return itemList;
}
}
});
As I know I have to return something, because it's a promise.
So If I return empty list if the data is null, the app recieves empty list, while the first call is still fetching the data and making a list.
Okay the issue was it's querySnapshot.docs and not querySnapshot.doc

Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null. Don't know the reason

I know this error has been answered already man times but i think my condition is bit different. My flutter was running nice till now without any dificulty. But suddenly it started giving me this error during run of app.It is not opening on app on installing.This error just keeps coming during installation of app and i don't know from where its coming.
Please guide me how to find the location of problem and how to resolve it.
This error is probably accuring because you are giving a null value to jsonDecode:
var jsonString = null;
var parsed = jsonDecode(jsonString);
print(parsed.length);
// NoSuchMethodError: The getter 'length' was called on null.
Search your project for jsonDecode or json.decode and ether don't call it when jsonString is null and show an error message, or replace it with a default jsonString:
var jsonString = null;
const defaultJson = '{}';
var parsed = jsonDecode(jsonString ?? defaultJson);
print(parsed.length);
// 0

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

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 = [];

Trouble with testing using MockClient in Flutter

I am trying to write a simple test in flutter using MockClient, but I can't seem to get it to work.
Here is the code I am trying to test:
getItemById(int id) async {
final response = await client.get("$_host/item/$id.json");
final decodedJson = json.decode(response.body);
return Item.fromJson(decodedJson);
}
Here is the test code:
test("Test getting item by id", () async {
final newsApi = NewsAPI();
newsApi.client = MockClient((request) async {
final jsonMap = {'id': 123};
Response(json.encode(jsonMap), 200);
});
final item = await newsApi.getItemById(123);
print("Items: ${item.toString()}"); //<-- dosen't print anything.
expect(item.id , 123);
});
When I run the test, it fails with the following message:
NoSuchMethodError: The getter 'bodyBytes' was called on null.
Receiver: null
Tried calling: bodyBytes
I am guessing the issue here is that nothing is returned from the MockClient when I make the call to the getItemById method, but I am not sure why.
I had the same exact issue. You have to return the Response
return Response(json.encode(jsonMap), 200);
Mock expects test function to be EXACTLY as you real function (including OPTIONAL parameters and so on). If both does not match it returns NULL and that is what is happening with your code. Double check to see where your test function is different of original function.