'The method '[]' can't be unconditionally invoked because the receiver can be 'null' | Firebase Database | Flutter
I'am getting the error 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 ('!'). Below is my code
import 'package:firebase_database/firebase_database.dart';
class Users {
String? id;
String? email;
String? name;
String? phone;
Users({
this.id,
this.email,
this.name,
this.phone,
});
Users.fromSnapshot(DataSnapshot dataSnapshot) {
id = dataSnapshot.key!;
email = dataSnapshot.value['email'];
name = dataSnapshot.value['name'];
phone = dataSnapshot.value['phone'];
}
}
The Error is in the last 3 lines
email = dataSnapshot.value['email'];
name = dataSnapshot.value['name'];
phone = dataSnapshot.value['phone'];
I have already added null safety operators. But it still shows an error.
Solution 1:[1]
A DataSnapshot object does not necessarily have a value, so its value property may be null. You need to check whether the snapshot has a value, before trying to read properties from it:
Users.fromSnapshot(DataSnapshot dataSnapshot) {
id = dataSnapshot.key!;
if (dataSnapshot.value != null) {
email = dataSnapshot.value!['email'];
name = dataSnapshot.value!['name'];
phone = dataSnapshot.value!['phone'];
}
}
Note the added if statements, and the ! marks that Pokaboom also commented about.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
