0

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.

  • Can you check here? https://stackoverflow.com/questions/67575893/the-method-cant-be-unconditionally-invoked-because-the-receiver-can-be-nu – zafercaliskan Feb 23 '22 at 11:47
  • Does this answer your question? [The method '\[\]' can't be unconditionally invoked because the receiver can be 'null'](https://stackoverflow.com/questions/67575893/the-method-cant-be-unconditionally-invoked-because-the-receiver-can-be-nu) – ibhavikmakwana Feb 23 '22 at 12:19
  • 1
    add `!` before `['email']` so `dataSnapshot.value!['email'];` but be sure that it will never be `null` – Pokaboom Feb 23 '22 at 12:35

2 Answers2

0

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0
 Users.fromSnapshot(DataSnapshot dataSnapshot) {
    List<User> userData = dataSnapshot.value!.toList();
    id = dataSnapshot.key!;
    email = userData['email'];
    name = userData['name'];
    phone = userData['phone'];
  }

maybe this work

Abdualiym
  • 179
  • 1
  • 9