Roxx
Roxx

Reputation: 3986

JSON Parse not parsing in Flutter if some object is empty

I have a signup form and the backend is PHP. PHP returning success, error data as JSON.

Below is my JSONParse file.

import 'dart:convert';

Signup signupFromJson(String str) => Signup.fromJson(json.decode(str));

String signupToJson(Signup data) => json.encode(data.toJson());

class Signup {
    Errors errors;
    bool success;

    Signup({
        this.errors,
        this.success,
    });

    factory Signup.fromJson(Map<String, dynamic> json) => Signup(

        errors: Errors.fromJson(json["errors"]),
        success: json["success"],
    );

    Map<String, dynamic> toJson() => {
        "errors": errors.toJson(),  
        "success": success,
    };
}

class Errors {
    String password1;
    String email1;
    String name;

    Errors({
        this.password1,
        this.email1,
        this.name,
    });

    factory Errors.fromJson(Map<String, dynamic> json) => Errors(
        password1: json["Password1"],
        email1: json["Email1"],
        name: json["Name"],
    );

    Map<String, dynamic> toJson() => {
        "Password1": password1,
        "Email1": email1,
        "Name": name,
    };
}

Here is sample JSON Data.

If login is failed due to some condition not met.

{"errors":{"Email1":"Email could not be empty",
"Password1":"Password could not be empty",
"Name":"Your name must be between 3 to 30 characters!"},
"success":false}

If login successful

{"success":false}

My JSONParse is working properly if condition not met. I mean it retuning all the errors and Success false.

But if login is successful then it is not working, by checking more I found data is coming fine from PHP.

Signup signupFromJson(String str) => Signup.fromJson(json.decode(str)); - Data is coming in str variable.

factory Signup.fromJson(Map<String, dynamic> json) => Signup(

            errors: Errors.fromJson(json["errors"]), -- If error is nulll then it is not checking the success.
            success: json["success"],
        );

The issue coming here when errors are null then it moved out didn't goto the success section.

What am I doing wrong here?

Upvotes: 1

Views: 1599

Answers (1)

Viren V Varasadiya
Viren V Varasadiya

Reputation: 27137

If you get success then you will not get errors, so you have to check null aware where you are passing to error class too.

In Signup.fromJson :

 errors: Errors.fromJson(json["errors"] ?? {}),

In Error Class

 factory Errors.fromJson(Map<String, dynamic> json) => Errors(
        password1: json["Password1"] ?? '',
        email1: json["Email1"] ?? '',
        name: json["Name"] ?? '',
    );

Upvotes: 2

Related Questions