skip to Main Content

My problem

I have a model in which I read JSON responses but I get this problem and i tried used stop the nulls but it doesn’t work.

My solution

I used the nullable type but I get still this error.

My Json :

{
    "success": true,
    "status_code": 200,
    "error": null,
    "data": {
        "message": "sussecc!",
        "has_paginate": 0,
        "results": {
            "user": {
                "id": 1,
                "full_name": "emin",
                "phone_number": "+1125585",
                "admin_role": "0",
                "national_id": "21",
                "address": null,
                "is_active": "1",
                "email": null,
                "email_verified_at": "2023-12-04 20:41:41",
                "created_at": "2023-12-04T17:11:42.000000Z",
                "updated_at": "2023-12-04T17:11:42.000000Z"
            },
            "token": "31|ssasdsdfsdgeedewfsdvfdbdfve3svxfb"
        }
    }
}

My Model Class :

class ModelLoginService {
  ModelLoginService({
    required this.success,
    required this.statusCode,
    required this.error,
    required this.data,
  });
  late final bool success;
  late final int statusCode;
  late final dynamic? error;
  late final Data? data;

  ModelLoginService.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    statusCode = json['status_code'];
    error = Error.fromJson(json['error']);
    data = Data.fromJson(json['data']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['success'] = success;
    _data['status_code'] = statusCode;
    _data['error'] = error!.toJson() == null ? null : error.toJson();
    _data['data'] = data!.toJson() == null ? null : error.toJson();
    return _data;
  }
}

class Error {
  Error({
    required this.message,
    required this.errors,
  });
  late final String? message;
  late final Errors? errors;

  Error.fromJson(Map<String, dynamic> json) {
    message = json['message'];
    errors = Errors.fromJson(json['errors']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['message'] = message!;
    _data['errors'] = errors!.toJson().isEmpty;
    return _data;
  }
}

class Errors {
  Errors({
    required this.reason,
    required this.message,
  });
  late final String reason;
  late final String message;

  Errors.fromJson(Map<String, dynamic> json) {
    reason = json['reason'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['reason'] = reason;
    _data['message'] = message;
    return _data;
  }
}

class Data {
  Data({
    required this.message,
    required this.hasPaginate,
    required this.results,
  });
  late final String message;
  late final int hasPaginate;
  late final Results results;

  Data.fromJson(Map<String, dynamic> json) {
    message = json['message'];
    hasPaginate = json['has_paginate'];
    results = Results.fromJson(json['results']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['message'] = message;
    _data['has_paginate'] = hasPaginate;
    _data['results'] = results.toJson();
    return _data;
  }
}

class Results {
  Results({
    required this.user,
    required this.token,
  });
  late final User user;
  late final String token;

  Results.fromJson(Map<String, dynamic> json) {
    user = User.fromJson(json['user']);
    token = json['token'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['user'] = user.toJson();
    _data['token'] = token;
    return _data;
  }
}

class User {
  User({
    required this.id,
    required this.fullName,
    required this.phoneNumber,
    required this.adminRole,
    required this.nationalId,
    required this.address,
    required this.isActive,
    required this.email,
    required this.emailVerifiedAt,
    required this.createdAt,
    required this.updatedAt,
  });
  late final int id;
  late final String fullName;
  late final String phoneNumber;
  late final String adminRole;
  late final String nationalId;
  late final String? address;
  late final String isActive;
  late final String? email;
  late final String emailVerifiedAt;
  late final String createdAt;
  late final String updatedAt;

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    fullName = json['full_name'];
    phoneNumber = json['phone_number'];
    adminRole = json['admin_role'];
    nationalId = json['national_id'];
    address = json['address'] == null ? null : json['address'];
    isActive = json['is_active'];
    email = json['email'] == null ? null : json['email'];
    emailVerifiedAt = json['email_verified_at'];
    createdAt = json['created_at'];
    updatedAt = json['updated_at'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['full_name'] = fullName;
    _data['phone_number'] = phoneNumber;
    _data['admin_role'] = adminRole;
    _data['national_id'] = nationalId;
    _data['address'] = address;
    _data['is_active'] = isActive;
    _data['email'] = email;
    _data['email_verified_at'] = emailVerifiedAt;
    _data['created_at'] = createdAt;
    _data['updated_at'] = updatedAt;
    return _data;
  }
}

My service for get JSON

class ServiceLogin extends GetConnect implements GetxService {
  Map<String, String> authorizationh = {};
  Map<String, dynamic> bodyMap = {};
  String username = "", password = "";

  Future<ModelLoginService> postData() async {
    bodyMap = {
      'full_name': 'admin',
      'password': 'c1992885',
    };

    var response = await post('http://test.com/admin/api/login', bodyMap);

    print('response.body ${response.body}');
    return ModelLoginService.fromJson(response.body);
  }
}

Error Log

Performing hot restart...
Waiting for connection from debug service on Edge...
Restarted application in 743ms.
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
[GETX] Instance "ApiController" has been created
[GETX] Instance "ApiController" has been initialized
response.body null
Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'Null'
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 294:3       throw_
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 127:3       castError
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 818:12  cast
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/classes.dart 652:14     as_C
packages/shndz_panel/services/service_login.dart 21:30                            postData
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50                <fn>
dart-sdk/lib/async/zone.dart 1661:54                                              runUnary
dart-sdk/lib/async/future_impl.dart 162:18                                        handleValue
dart-sdk/lib/async/future_impl.dart 846:44                                        handleValueCallback
dart-sdk/lib/async/future_impl.dart 875:13                                        _propagateToListeners
dart-sdk/lib/async/future_impl.dart 655:5                                         [_completeError]
dart-sdk/lib/async/future_impl.dart 745:7                                         callback
dart-sdk/lib/async/schedule_microtask.dart 40:11                                  _microtaskLoop
dart-sdk/lib/async/schedule_microtask.dart 49:5                                   _startMicrotaskLoop
dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 181:7                <fn>

I used nullable type in flutter in my model and expected this problem not to occur and i can’t find the best way to solve it

2

Answers


  1. Your JSON response seems to have some nullable fields, such as address and email. When mapping these fields to your model, you need to account for the possibility that these fields might be null in the JSON.

    In your User.fromJson method, you’re already handling the conversion of nullable fields like address and email by checking if they are null in the JSON and assigning them accordingly:

    address = json['address'] == null ? null : json['address'];
    email = json['email'] == null ? null : json['email'];
    

    However, the issue might arise if the error or data fields in your JSON response are null. Your ModelLoginService.fromJson method assumes these fields will always contain valid JSON objects, causing the error when encountering null.

    To handle this, you should check for nullability at each level when parsing JSON. For example, in ModelLoginService.fromJson, you can modify the parsing of error and data:

    error = json['error'] != null ? Error.fromJson(json['error']) : null;
    data = json['data'] != null ? Data.fromJson(json['data']) : null;
    

    This way, if error or data is null in the JSON, you assign null to the corresponding variable in your model class, avoiding potential errors.

    Similarly, in your Data.fromJson method, you can adjust the parsing of results:

    results = json['results'] != null ? Results.fromJson(json['results']) : Results();
    

    This approach ensures that if any part of your JSON response is null, the corresponding object in your model will also be null or a default/empty object.

    Remember to handle these nullable objects appropriately in your code wherever you’re using this model to avoid null pointer exceptions.

    Login or Signup to reply.
  2. Use this optional model instead of required model however it is always recommended to to use data part of json and get. check on success or status code
    import ‘dart:convert’;

    class UserLoginModel {
        final bool? success;
        final int? statusCode;
        final dynamic error;
        final Data? data;
    
        UserLoginModel({
            this.success,
            this.statusCode,
            this.error,
            this.data,
        });
    
        factory UserLoginModel.fromRawJson(String str) => UserLoginModel.fromJson(json.decode(str));
    
        String toRawJson() => json.encode(toJson());
    
        factory UserLoginModel.fromJson(Map<String, dynamic> json) => UserLoginModel(
            success: json["success"],
            statusCode: json["status_code"],
            error: json["error"],
            data: json["data"] == null ? null : Data.fromJson(json["data"]),
        );
    
        Map<String, dynamic> toJson() => {
            "success": success,
            "status_code": statusCode,
            "error": error,
            "data": data?.toJson(),
        };
    }
    
    class Data {
        final String? message;
        final int? hasPaginate;
        final Results? results;
    
        Data({
            this.message,
            this.hasPaginate,
            this.results,
        });
    
        factory Data.fromRawJson(String str) => Data.fromJson(json.decode(str));
    
        String toRawJson() => json.encode(toJson());
    
        factory Data.fromJson(Map<String, dynamic> json) => Data(
            message: json["message"],
            hasPaginate: json["has_paginate"],
            results: json["results"] == null ? null : Results.fromJson(json["results"]),
        );
    
        Map<String, dynamic> toJson() => {
            "message": message,
            "has_paginate": hasPaginate,
            "results": results?.toJson(),
        };
    }
    
    class Results {
        final User? user;
        final String? token;
    
        Results({
            this.user,
            this.token,
        });
    
        factory Results.fromRawJson(String str) => Results.fromJson(json.decode(str));
    
        String toRawJson() => json.encode(toJson());
    
        factory Results.fromJson(Map<String, dynamic> json) => Results(
            user: json["user"] == null ? null : User.fromJson(json["user"]),
            token: json["token"],
        );
    
        Map<String, dynamic> toJson() => {
            "user": user?.toJson(),
            "token": token,
        };
    }
    
    class User {
        final int? id;
        final String? fullName;
        final String? phoneNumber;
        final String? adminRole;
        final String? nationalId;
        final dynamic address;
        final String? isActive;
        final dynamic email;
        final DateTime? emailVerifiedAt;
        final DateTime? createdAt;
        final DateTime? updatedAt;
    
        User({
            this.id,
            this.fullName,
            this.phoneNumber,
            this.adminRole,
            this.nationalId,
            this.address,
            this.isActive,
            this.email,
            this.emailVerifiedAt,
            this.createdAt,
            this.updatedAt,
        });
    
        factory User.fromRawJson(String str) => User.fromJson(json.decode(str));
    
        String toRawJson() => json.encode(toJson());
    
        factory User.fromJson(Map<String, dynamic> json) => User(
            id: json["id"],
            fullName: json["full_name"],
            phoneNumber: json["phone_number"],
            adminRole: json["admin_role"],
            nationalId: json["national_id"],
            address: json["address"],
            isActive: json["is_active"],
            email: json["email"],
            emailVerifiedAt: json["email_verified_at"] == null ? null : DateTime.parse(json["email_verified_at"]),
            createdAt: json["created_at"] == null ? null : DateTime.parse(json["created_at"]),
            updatedAt: json["updated_at"] == null ? null : DateTime.parse(json["updated_at"]),
        );
    
        Map<String, dynamic> toJson() => {
            "id": id,
            "full_name": fullName,
            "phone_number": phoneNumber,
            "admin_role": adminRole,
            "national_id": nationalId,
            "address": address,
            "is_active": isActive,
            "email": email,
            "email_verified_at": emailVerifiedAt?.toIso8601String(),
            "created_at": createdAt?.toIso8601String(),
            "updated_at": updatedAt?.toIso8601String(),
        };
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search