Home > Mobile >  Can't use is operator to check type of return data
Can't use is operator to check type of return data

Time:09-30

I have a problem with checking the return data type from the server with the defined model.

I can't compare the returned data type of UserTest. I want to check that the returned data is of type UserTest, I logged respond and it has a property of UserTest but (response is UserTest) not run.

Future<dynamic> loginApp() async {
try {
  final Map<String, dynamic> dataForm = new Map<String, dynamic>();

  dataForm["name"] = "[email protected]";      // hard for test
  dataForm["job"] = "123456";                   // hard for test
           
  var bodyJson = json.encode(dataForm);
  print("bodyJson $bodyJson");     // {"name":"[email protected]","job":"123456"}

  var response = await _apiNetworkPOST(endPoint: 'users', body: bodyJson);

  if (response is Map<String, dynamic>) {
    print("I am UserTest $response");  //=>> Data is available here

    if (response is UserTest) {   //=>> it not come here
      return UserTest.fromJson(response);
    }
  }

  return ErrorJson(message: response.toString());
} on Exception catch (e) {
  return FetchDataException(e.toString());
}
}

print('I am UserTest $response'); result

{name: [email protected], job: 123456, id: 392, createdAt: 2021-09-29T09:43:31.290Z}

My UserTest class:

class UserTest {

UserTest({
    this.name,
    this.job,
    this.id,
    this.createdAt,
  });

  final String? name;
  final String? job;
  final String? id;
  final DateTime? createdAt;

  factory UserTest.fromRawJson(String str) =>
      UserTest.fromJson(json.decode(str));

  String toRawJson() => json.encode(toJson());

  factory UserTest.fromJson(Map<String, dynamic> json) => UserTest(
        name: json["name"],
        job: json["job"],
        id: json["id"],
        createdAt: DateTime.parse(json["createdAt"]),
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "job": job,
        "id": id,
        "createdAt": createdAt?.toIso8601String(),
      };
}

Thank you for all answer!

CodePudding user response:

This construct would only work if UserTest would inherit from the Map. There is no operator in dart to check if a map fits an object. You have to check manually if the Map contains the expected keys.

  • Related