Home > Software design >  flutter: how to use type or generic to Map?
flutter: how to use type or generic to Map?

Time:11-03

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?

CodePudding user response:

You just can initialize it, for example:

TestModel a = TestModel('huh', 'whaaat!?');
  • Related