Home > Software engineering >  I get an error with snapshot.data()["~~~"] flutter
I get an error with snapshot.data()["~~~"] flutter

Time:11-23

I'm trying to get the value from Firestore with the following code. But I'm sorry I got this error. Help me

DocumentSnapshot snapshot = await FirebaseFirestore.instance.collection("users").doc(user.uid).get();

print(snapshot.data()["location"] as String);

Details of 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 ('!').

I tried various things, for example after "data()" ! Turn on

enter image description here

CodePudding user response:

you need to add null check operator to make sure that receiver is not null.

print(snapshot.data()!["location"] as String);

CodePudding user response:

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 ('!').

As you might be able to guess, you are getting an error because if the snapshot has no data, it will return null, which will error. Here are some ways of fixing it:

  1. adding a bang operator (!) (But you say this did not fix the issue?)
print(snapshot.data()!['location'] as String);

note the ! after data(), the bang operator tells dart to ignore a nullable value, this code will work as long as snapshot.data() is not null, of course, this is not safe, because snapshot.data() could be null, so here is an obvious solution:

var data = snapshot.data();
if (data != null) {
  print(data!['location'] as String);
}

this should work, because now if data is null, the print statement will simply not run.

  1. adding a ? operator
print(snapshot?['location']);

note the ? after data(), the ? operator will escalate a null value, so if snapshot.data() is not null, snapshot.data()?['location'] will be equal to snapshot.data()['location'], but if snapshot.data() is null, snapshot.data()?['location'] will be equal to null instead of throwing an error.

  1. Adding a ?? operator
print(snapshot.data()?['location'] ?? 'the value was null');

Here, it is necessary to use both the ? operator to escalate the null value and the ?? operator.

The ?? operator will output the value on the left if the value is not null and will output the value on the right if the value on the left is null, so in this case, if snapshot.data() is null, that will escalate the null value, meaning snapshot.data()?['location'] will be null, which in turn means that instead of printing 'null', the ?? operator will print 'the value was null'

So to conclude, if you are sure the value is not null, you can use the bang operator !, if you are not sure, then you can use a combination of ? and ?? to your advantage.

  • Related