0
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?

1
  • 1
    Why can't you use .fromJson? Won't TestModel a = TestModel.fromJson({'firstName': 'huh', 'lastName': 'whaaat!?'}); work?
    – Marcel
    Nov 2, 2021 at 16:52

1 Answer 1

1

You just can initialize it, for example:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.