Home > other >  Initialize with flexible keys in fromJson
Initialize with flexible keys in fromJson

Time:11-12

I want to set Movie/TV information values that fetch form API, but what some JSON keys are different, but values types are same the difference is not so much to create another model for that, so I want to continue with main model class.

For example title is key for movie but for TV is name key in JSON, and some other keys that are different.

I've tried to solve it with checking, but it did not work:

 final String? title;
 factory Result.fromJson(Map<String, dynamic> json) => Result(
        title: json["title"] == Null ? json["name"] : json["title"],
...
)

As I mentioned that work for Movie but for TV will not work, error that shows for that:

Unhandled Exception: type 'Null' is not a subtype of type 'String'

I also tried this method, but it didn't work for both parts as before:

 title: json["name"] ?? json["title"]

How can I handle initialization with flexible keys?

CodePudding user response:

Null is not string type, you can check with null

json["title"] == null ? json["name"] : json["title"],
  • Related