Home > Software engineering >  Why compiler assuming `json['x'] = int?`?
Why compiler assuming `json['x'] = int?`?

Time:01-25

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? ?

CodePudding user response:

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.

  •  Tags:  
  • Related