Ahmed
Ahmed

Reputation: 122

check if null value inside Json response flutter

user = User(
    membership:json.decode(response.body["MembershipStatus"],
    userCode:  json.decode(response.body) ["ResultObject"]["UserCode"],
    username:  json.decode(response.body) ["ResultObject"]["UserName"] ?? "",
    startDate:json.decode(response.body) ["ResultObject"]["MemberShipDetails"]["StartDate"]?? "",
    endDate: json.decode(response.body)  ["ResultObject"]["MemberShipDetails"]["EndDate"]?? "",
);

How to check for null value when initialize constructor in flutter,

If value of "MemberShipDetails" is null the app will crash, How to check the value of "MemberShipDetails" before getting "StartDate" value

Upvotes: 0

Views: 636

Answers (1)

julemand101
julemand101

Reputation: 31219

You can use ? like this to return null if the previous result was null:

import 'dart:convert';

void main() {
  dynamic value =
      jsonDecode('{"MemberShipDetails": null}')?["MemberShipDetails"]
              ?["EndDate"] ??
          'Hey, we got a null!';
  print(value); // Hey, we got a null!
}

Upvotes: 1

Related Questions