flutter: how to use type or generic to Map?


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!?'};

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?


You just can initialize it, for example:

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

Answered By – MerdanDev

Leave a Comment