Dart null

Dart convert null to String?

If you ever work with Dart and wanna convert null to String? How does it work? Actually it’a bad idea. Don’t convert your null to String. You will get unexpected behavior. Your app might not crush.

Here I got json data from the server and I was converting it to object using fromJson method. But one of the fields was empty.

I mean I did not return a field which I was supposed to return from the server the side.

Here my field down_num is mentioned, but from the backend side I did not return the field. So it’s already null.

And what happens If I give this to my application or further use it in the code? Here I am using in the front end Flutter app.

Here you see we are doing courseItem.down_num.toString(), but this would convert null to null string. But null is not equal to null string.

You see the last line shows null. So the idea is don’t convert null to String. Just check the field before using that the item exist or not. If it does not exist then use a call back value.

And you can also see it from the hashCode. The hashCode for null and null string are different.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *