Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why compiler assuming `json['x'] = int?`?

class Point {
  int x;
  int y;
  Point(this.x, this.y);
  Point.zero()
      : x = 0,
        y = 0;
  Point.fromJson({required Map<String, int> json})
    :x = json['x'], //Error : `The initializer type 'int?' can't be assigned to the field type 'int'`
     y = json['y']; // Error :`The initializer type 'int?' can't be assigned to the field type 'int'`
}

As you can see the argument json here is Map<String , int> so why am getting this error here.When both are non-nullable here ?
Why compiler assuming json['x'] = int? ?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Because the [] operator on Map returns a nullable by spec:

V? operator [](Object? key)

The value for the given key, or null if key is not in the map.

https://api.dart.dev/stable/2.15.1/dart-core/Map/operator_get.html

So if you are asking for a key that is not in your Map you will get a null value back and not an exception.

If you are 100% sure json['x'] will always work and want the application to crash in case this is not the case, you can use json['x']!. Alternative, you need to provide default values or other type of handling in case these values is not in the map.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading