0

I have this function with scoped model in which I want to have a firebase increment to snapshot when the button is pressed, but It returns ˜The getter 'documentID' was called on null.˜, it changes the state of my icon but the number is not incremented. If I give the name of the document it works fine, but I don't want to specify it. Any thoughts on what could be the solution?

void main() {
runApp(EaiCasimiro());
}



class EaiCasimiro extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ScopedModel<LikesModel>(
    model: LikesModel(),
    child: MaterialApp(
      title: "E aí,  Casimiro?",
      home: HomeScreen(),
      debugShowCheckedModeBanner: false,
      )
    );
   }
}


class LikesModel extends Model {

DocumentSnapshot snapshot;




bool _liked = true;

static LikesModel of(BuildContext context) =>
  ScopedModel.of<LikesModel>(context, rebuildOnChange: true);


bool isLiked() => _liked;




void pressed(){
_liked = !_liked;
notifyListeners();
 }

void changeLikes() {
Firestore.instance
    .collection("lanchonetes")
    .document(snapshot.documentID)
    .updateData({'likes': FieldValue.increment(_liked ? -1 : 1)});


    }

}
  • 1
    Please take care to format your code well in your question so it's easier to read. It seems you've lost a lot of indentation, and that makes it difficult. You can mark whole blocks of text as code by simply starting and end the entire block with three backticks: ``` – Doug Stevenson Jan 08 '20 at 00:18
  • Thanks for your tip Doug, I`ll try to make it better next time I post a code. – Ricardo Oscar Kanitz Jan 08 '20 at 00:32
  • 1
    You can always go back and edit the code right now by clicking the "edit" link at the bottom of the question and making changes in the editor. – Doug Stevenson Jan 08 '20 at 00:33

1 Answers1

3

Since you have a lot of code here, but haven't noted a specific line where the error occurs, I'll guess it happens here:

Firestore.instance
    .collection("lanchonetes")
    .document(snapshot.documentID)
    .updateData({'likes': FieldValue.increment(_liked ? -1 : 1)});

It took me a while to find where you defined snapshot, but I found it here:

DocumentSnapshot snapshot;

Since you didn't assign a value when you declared it, it's going to have an initial value of null. So, when you use it in the query like this: snapshot.documentID, you're getting that error.

Make sure snapshot is defined before you use it.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Do you know how I can define it? I tried different ways, searched a lot, but the closest I got was with a .forEach, but it incremented all my documents. – Ricardo Oscar Kanitz Jan 08 '20 at 23:31