DEV Community

AYUSH GOYAL 22110009
AYUSH GOYAL 22110009

Posted on

Can anyone help??

class UserModel {
  String? token;
  bool? success ;

  UserModel({this.token , this.success});

  UserModel.fromJson(Map<String, dynamic> json) {
    token = json['authtoken'];
    success = json['success'];

  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['token'] = this.token;
    data['success'] = this.success;
    return data;
  }
}
Enter fullscreen mode Exit fullscreen mode

is fromJson allready defined (is it a inbuilt funciton? ) , is it a static funciton because we only call static function like Classname.staticfunction , why can it be writen like :-

fromJson(Map<String, dynamic> json) {
    this.token = json['authtoken'];
    this.success = json['success'];
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
ferceg profile image
ferceg

I'm not sure what you want to achieve here but this works for me on DartPad:

class UserModel {
  String? token;
  bool? success ;

  UserModel({this.token , this.success});

  void fromJson(Map<String, dynamic> json) {
    token = json['authtoken'];
    success = json['success'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};
    data['token'] = token;
    data['success'] = success;
    return data;
  }
}


void main() 
{
  var json = {"authtoken": "xxx", "success": true};
  var user = UserModel()..fromJson(json);
  print(user.token);
  print(user.success);
  print(user.toJson());
}

Enter fullscreen mode Exit fullscreen mode