1

I have this User class and then a Firestore Document, that may or may not contain a photoURL or some other values. The problem is, that when I try to create an user I get this exception because some of the values are Null.

I've tried to handle it like this:

var photoURL = snapshot.data['photoURL']  ??= '';

but it seems it doesn't work.

Can anyone explain best practices handling Null values in Dart/Flutter respectively?

EDIT: I'm checking if snapshot.exists before and if I create the user omitting the values I know are Null, it creates it properly.

EDIT 2: I've found the problem appears when I try to handle empty List like this:

var favorites =  snapshot.data['favorites'] ?? [''];
3
  • are you doing snapshot.hasData check before looking for 'photoURL' ? Commented Sep 13, 2019 at 15:06
  • if (snapshot.exists) Commented Sep 13, 2019 at 15:08
  • i've tried this before and it doesn't work, then I've read this article medium.com/@thinkdigitalsoftware/… and I've changed it to ??= Commented Sep 13, 2019 at 15:25

1 Answer 1

3

It seems I was initialized the value the wrong way when I converted it to Json.

I handle the empty Array like this

Map<String, dynamic> toJson() => {
   'favorites' : favorites ?? '',
}

when it should be:

Map<String, dynamic> toJson() => {
   'favorites' : favorites ?? [''],
}

So it was throwing when I tried to assign an empty Array to String.

Sign up to request clarification or add additional context in comments.

1 Comment

just so you know [''] is not an empty array. It's an array containing 1 element, an empty string. An empty array would be []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.