Flutter firebase: Bad state: field does not exist within the DocumentSnapshotPlatform - flutter

I'm getting this error:
Bad state: field does not exist within the DocumentSnapshotPlatform
with the following code:
static List<Report?> reportListFromSnapshot(QuerySnapshot snapshot) {
return snapshot.docs.map<Report?>((report) {
return Report(
type: report['type'],
reason: report['reason'],
reportId: report['id'],
chat:
(report['chat'] == null) ? null : Chat.chatFromMap(report['chat']),
stingray: Stingray.stingrayFromDynamic(report['stingray']),
reporterUser: User.fromDynamic(report['reporterUser']),
reportTime: report['reportTime'].toDate(),
);
}).toList();
}
Its failing on the first map,
type: report['type'],
and when i look at it in debug mode, it shows the data i am looking for:
As you can see from the screenshot, 'type' exists with a value of 'chat report'. Any idea why this is breaking?
Thanks!

You are supposed to call .data() on report
static List<Report> reportListFromSnapshot(QuerySnapshot snapshot) {
final List<Report> reports = [];
for (final doc in snapshot.docs) {
final report = doc.data() as Map<String, dynamic>?; // you missed this line.
if (report == null) continue;
reports.push(
Report(
type: report['type'] as String,
reason: report['reason'] as String,
reportId: report['id'] as String,
chat: (report['chat'] == null)
? null
: Chat.chatFromMap(report['chat']),
stingray: Stingray.stingrayFromDynamic(report['stingray']),
reporterUser: User.fromDynamic(report['reporterUser']),
reportTime: (report['reportTime'] as Timestamp).toDate(),
),
);
}
return reports;
}
// I returned List<Report> not List<Report?>
Check out this link on how to use withConverter so you do not have to manually convert models.

The problem turned out to be larger in scope than i thought. I was uploading a map object to firebase rather than just a document, and that map was attempting to be read, which is where the error occurred due to it only having one value in the document snapshot.

Maybe you have typo in your field which does not match with your model fields. So the idea is that, your fields in your model has to match with the fields in your firebase snapshot fields.
enter link description here

Related

RangeError (RangeError (index): Invalid value: Valid value range is empty: 0) with Cloud Firestore

I know this question has been asked alot but this is very different, I am querying my firestore database to return users that a person searches. Then it returns the data of the specific person you are searching for.
here is the code
await firestore
.collection('users')
.where("email", isEqualTo: _search.text)
.get()
.then((value) {
setState(() {
userMap = value.docs[0].data();
isLoading = false;
});
});
The problem is whenever I input a value in the search bar that is NOT a user on the database, it gives me that error "RangeError (RangeError (index): Invalid value: Valid value range is empty: 0)". I understand it's because the thing being searched for doesn't exist yet but I have no idea how to fix it, please help!
You need to add a check with if statement that the length of value.docs is not equal to zero.
.then((value) {
if(value.docs.length.isNotEmpty){
setState(() {
userMap = value.docs[0].data();
isLoading = false;
});
}
Write an if statement in the .then fallback function to see if value.docs.length is greater then 0 and if yes, use the code you have, and if not (in the else) it doesn't exist and write what it should do in that situation.

Map getter not pulling items by index properly

I have a Map of <String, CartItem> which is a custom class, and I am trying to return specific values from that Map, but every time I do return them in the format item[I], I get a "Null check operator used on a null value." Is there a different way I should be calling this?
Details
I have a map of _items with a public getter that returns those items:
class Cart with ChangeNotifier {
Map<String, CartItem> _items = {};
Map<String, CartItem> get items {
return {..._items};
}
Followed by a function that adds new items to the Map:
void addItem(
String productId,
double price,
String title,
) {
if (_items.containsKey(productId)) {
_items.update(
productId,
(existingCartItem) => CartItem(
id: existingCartItem.id,
title: existingCartItem.title,
price: existingCartItem.price,
quantity: (existingCartItem.quantity + 1),
),
);
} else {
_items.putIfAbsent(
productId,
() => CartItem(
id: DateTime.now().toString(),
title: title,
price: price,
quantity: 1,
),
);
}
print(items.length);
print(items[0]);
print(items);
notifyListeners();
}
When I call addItem, this is the output I get from those three print statements - it appears calling as items[0] returns null, even though the length and the full items list print properly:
Performing hot restart...
Restarted application in 1,483ms.
flutter: 1
flutter: null
flutter: {p1: Instance of 'CartItem'}
Then whenever I call that Cart Provider looking for a specific item in the Map:
child: ListView.builder(
itemCount: cart.itemCount,
itemBuilder: (ctx, i) => CartItem(cart.items[i]!)),
)
I get a "Null check operator used on a null value" error. Why is this way of calling the items in the map returning null?
You seem to assume that items[0] works like an array and returns the first element. It does not. A Map has an indexer by key. It returns the item, with the given key. That is the whole point of a map, being able to look up items by key. You set your productId as a key, so to find it you would need to use items[productId].
Some thoughts: does your cart items needs to be a map? If all you want is enumerating through it, it would work if you made it a simple list instead. Then the numeric indexer would work again.
If it needs to be a map, you can use items.values to iterate through all the values. But please note that a map is not ordered. Again, if you need an ordered list, it would be better to use a list in the first place.

How to add Firestore data into List<List>

I want to add Firestore data into List to display it in a pdf report, this way wouldn't work properly I mean they not show the data in the list and display some error I don't know what the problem?
Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform"
theData() async {
await FirebaseFirestore.instance
.collection('QFS')
.snapshots()
.forEach((QuerySnapshot snapshot) {
for (int index = 0; index < snapshot.docs.length; index++) {
List<List> listOfData = [];
listOfData
.add({snapshot.docs[index]["commodity"]}.toList());
print(listOfData);
}
});
}
I think you should try optimising your code using forEach() loop instead of for() loop and you should try using docs[index].get(‘commodity’) instead of docs[index][“commodity”].
You can refer to these stackoverflow links for more insight: Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform, How to fix Bad state: field does not exist within the DocumentSnapshotPlatform.

Invalid Date Format - Flutter/Dart

It might be a simple solution but I have some problems with it. I have JSON response with user data like name, address, and birthday. However, birthDay is empty and I cannot parse it.
Error (only those lines occure):
Exception has occurred.
FormatException (FormatException: Invalid date format
)
I'm using tryParse and DateFormatter with null check but it seems to not work as I expect. Below you'll find part of code and JSON response:
Part of response:
birthDay: "" // as you see it's empty
bioInfo: ""
badges: List(6 items)
agreement5: false
Part of Profile Entity:
class ProfileEntity {
final String birthDay;
ProfileEntity.fromJson(Map<String, dynamic> json)
: birthDay = json['birthDay'],
}
Part of Profile Model:
class ProfileModel {
final DateTime birthDate;
ProfileModel({#required this.birthDate});
ProfileModel.fromEntities(
ProfileEntity profileEntity,
) : birthDate = DateTime.tryParse(profileEntity.birthDay), //place where I'm getting an error - value is null in this case.
//here I'm sending it to form field
Map<String, String> toFormFields() {
return {
'jform[birthDay]':
birthDate != null ? DateFormat("yyyy-MM-dd").format(birthDate) : "", //null check
}
}
}
Do you have any idea how to get rid of this? (Error message do not provide any info despite what I paste above in error part)
DateTime.tryParse does not expect null value.
You can replace this with DateTime.tryParse(profileEntity.birthDay ?? '') which will return null instead of throwing exception.
For ref: tryParse method
DateFormat('dd-MM-yyyy').parse(widget.initialDate);
remember you can change date format according to which you api sends date in my case 'dd-MM-yyy' in your case may be different format.

Handle null value in Dart / Flutter

I have this User class and then a Firestore Document, that may or may not contain a photoURL or some other values. The problem is, that when I try to create an user I get this exception because some of the values are Null.
I've tried to handle it like this:
var photoURL = snapshot.data['photoURL'] ??= '';
but it seems it doesn't work.
Can anyone explain best practices handling Null values in Dart/Flutter respectively?
EDIT: I'm checking if snapshot.exists before and if I create the user omitting the values I know are Null, it creates it properly.
EDIT 2: I've found the problem appears when I try to handle empty List like this:
var favorites = snapshot.data['favorites'] ?? [''];
It seems I was initialized the value the wrong way when I converted it to Json.
I handle the empty Array like this
Map<String, dynamic> toJson() => {
'favorites' : favorites ?? '',
}
when it should be:
Map<String, dynamic> toJson() => {
'favorites' : favorites ?? [''],
}
So it was throwing when I tried to assign an empty Array to String.