Home > Mobile >  "Don't cast a nullable value to a non nullable type" in Map when converting JSON to o
"Don't cast a nullable value to a non nullable type" in Map when converting JSON to o

Time:09-27

I just tried out the very_good_analysis package which includes also the cast_nullable_to_non_nullable lint rule.

And here is the code that gaves me the linter warning (initially, all casts look the the cast of a. Variables b and c are just showing what else I tried):

@immutable
class Foo {
  Foo.fromJson(Map<String, int> json):
    a = json['a'] as int, // Don't cast a nullable value to a non nullable type. (cast_nullable_to_non_nullable
    b = (json['b'] as int?)!, // Unnecessary cast
    c = json['c']! as int; // Unnecessary cast

  final int a;
  final int b;
  final int c;
}

So what is the correct way to convert this JSON map to a Foo object? And with correct I mean there are no warnings when using the very_good_analysis lints. Thanks a lot!

Edit

I found a working solution:

@immutable
class Foo {
  Foo.fromJson(Map<String, dynamic> json):
    a = json['a'] as int, 
    b = json['b'] as int, 
    c = json['c'] as int;

  final int a;
  final int b;
  final int c;
}

But can you please explain why Map<String, int> does not work and Map<String, dynamic> works? Is this a bug in the linter rule?

CodePudding user response:

It seems like that rule is just there to encourage using the ! operator over casting with as. This works for me with the very_good_analysis lints enabled:

class Foo {
  Foo.fromJson(Map<String, int> json)
      : a = json['a']!,
        b = json['b']!,
        c = json['c']!;

  final int a;
  final int b;
  final int c;
}

As for why the you didn't get a warning with Map<String, dynamic>: that lint is written to not fire for dynamic. You can see it in the source here. It's probably debatable but I would consider that the correct behavior. If you're using dynamic in your code you're already telling the language to effectively turn off compile-time type checking and just trust you instead.

  • Related