Home > database >  The method '[]' can't be unconditionally invoked because the receiver can be 'nu
The method '[]' can't be unconditionally invoked because the receiver can be 'nu

Time:01-07

      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

CodePudding user response:

Cast your value to Map<String,dynamic>

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

and then it probably must work for you.

CodePudding user response:

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.

  •  Tags:  
  • Related