[SOLVED] Flutter/Dart Make Missing Item in JSON Listview Automatically Anonymous?

Issue

I’ve got a Listview in Flutter which grabs JSON items from a MySQL database . Each item in the list contains a userid, username and avatar. Occasionally the user had been deleted so the database returns "NULL" for each column. How can I automatically assign "userid" to "1", "username" to "anonymous" and avatar to "anonymous.jpg"?

Here’s the class I’m using for the listview;

class AccountContent {
  String? name;
  String? avatar;
  String? userid;
      
  AccountContent({this.name, this.avatar, this.userid});

  AccountContent.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    avatar = "https://mysite/avatar.jpg";
    userid = json['userid'];    
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['avatar'] = this.avatar;
    data['userid'] = this.userid;    
    return data;
  }
} 

Solution

You can use default null check operator (??) to assign default value when the field is null.

class AccountContent {
  String? name;
  String? avatar;
  String? userid;
     
  AccountContent({this.name, this.avatar, this.userid});

  AccountContent.fromJson(Map<String, dynamic> json) {
    name = json['name'] ?? "1";
    avatar = "https://mysite/avatar.jpg" ?? "anonymous.jpg";
    userid = json['userid'] ?? "anonymous";    
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['avatar'] = this.avatar;
    data['userid'] = this.userid;    
    return data;
  }
} 

Answered By – Zakaria Hossain

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.