flutter: how to use type or generic to Map?

Issue

class TestModel {
  String? firstName, lastName;
  TestModel(this.firstName, this.lastName);

  TestModel.fromJson(Map<String, dynamic> json)
      : firstName  json['firstName'],
        lastName  json['lastName'];

}

I get that I can convert incoming json to TestModel. However, how can I assign TestModel type to a variable Map?

TestModel a  {'firstName': 'huh', 'lastName': 'whaaat!?'} as TestModel;

TestModel a or Map<TestModel> does not work, while

var a  {'firstName': 'huh', 'lastName': 'whaaat!?'};
print(TestModel.fromJson(a));

This works. How can I directly assign the model to the variable without using .fromJson, because I am directly getting the values from the TextField?

Solution

You just can initialize it, for example:

TestModel a  TestModel('huh', 'whaaat!?');

Answered By – MerdanDev

Leave a Comment