0
      Post fromSnapShot(DataSnapshot snapshot) {
    return Post(
        content: snapshot.value['Content'],
        commentsCount: commentsCount,
        likesCount: likesCount,
        color: color,
        timestamp: timestamp,
        hashtags: hashtags);
  }

i'm trying to create FromSnapShot method on my dataClass, i'm using firebase_database

but i keep getting this

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 aleardy tried to null check with ! but i get another error

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'

here's my pubspec.yaml

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  hooks_riverpod:
  flutter_hooks:
  firebase_auth:
  google_fonts: ^2.2.0
  flutter_glow: ^0.2.0
  cupertino_icons: ^1.0.2
  firebase_core: ^1.10.6
  firebase_database: ^9.0.4

dev_dependencies:
  flutter_test:
    sdk: flutter
YooobY
  • 11
  • 1
  • 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) – Mahmoud Abu Alheja Jan 06 '22 at 18:16

2 Answers2

0

Cast your value to Map<String,dynamic>

so Map<String,dynamic> postData = snapshot.value!

and then it probably must work for you.

Arti Scream
  • 121
  • 1
  • 14
  • now i get this "A value of type 'Object' can't be assigned to a variable of type 'Map?'. Try changing the type of the variable, or casting the right-hand type to 'Map?'" – YooobY Jan 06 '22 at 18:23
0

I added a null check to ensure that the variable will not be null. Can you try this out?

Post fromSnapShot(DataSnapshot snapshot) {
var myContent = snapshot.value['Content']?? '';
return Post(
    content: myContent,
    commentsCount: commentsCount,
    likesCount: likesCount,
    color: color,
    timestamp: timestamp,
    hashtags: hashtags);

}

When you try to null check with 'value['Content']!' the type will change, thus it will give an error.