Reputation: 153
im having an error stating "The method '[]' can't be unconditionally invoked because the receiver can be 'null'. Try making the call conditional (using '?.') or adding a null check to the target ('!')." Ive tried to add the '!' mark as stated and searching online but it doesn't resolve the issue. any ideas?
factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
return UserModel(
name: snapshot.data()["name"],
email: snapshot.data()['email'],
phoneNumber: snapshot.data()['phoneNumber'],
uid: snapshot.data()['uid'],
isOnline: snapshot.data()['isOnline'],
profileUrl: snapshot.data()['profileUrl'],
status: snapshot.data()['status'],
designation: snapshot.data()['designation'],
company: snapshot.data()['company'],
);
}
Upvotes: -1
Views: 3719
Reputation: 179
snapshot.data
with !
?
, !
. Simple as List with []
FutureBuilder<List<Orders>>( // 1
future: futureOrders,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(child: CircularProgressIndicator());
} else {
final List<Orders> orders = snapshot.data!; // 2
return ListView.builder(
itemCount: orders.length, // 3
itemBuilder: (context, index) => _cartItemWidget(
id: orders[index].id, // 3
cost: orders[index].cost, // 3
date: orders[index].createdAt)); // 3
}
},
)
Upvotes: 1
Reputation: 4666
That's because if snapshot.data()
is null
then you can't really access its fields, try null
checking it :
snapshot.data()?['name'] ?? ''
And according to docs data
method returns non-null map, so you can try also this :
(snapshot.data() as Map<String,dynamic>)['name']
Always assuming you allow null
values for name parameter. Otherwise you will need to null check it also
(snapshot.data() as Map<String,dynamic>)['name'] ?? ''
Upvotes: 1
Reputation: 326
Can you try like this
factory UserModel.fromSnapshot(DocumentSnapshot snapshot) {
return UserModel(
name: snapshot.data()["name"] ?? "",
email: snapshot.data()['email'] ?? "",
phoneNumber: snapshot.data()['phoneNumber'] ?? 0,
uid: snapshot.data()['uid'] ?? 0,
isOnline: snapshot.data()['isOnline'] ?? false,
profileUrl: snapshot.data()['profileUrl'] ?? ""
);
}
Upvotes: 0