Home > Net >  How to get data values and store in variables in flutter from json model class
How to get data values and store in variables in flutter from json model class

Time:08-29

I am a new in flutter but I have a good knowledge of java.

My Model Class

  UserDashboard({
    required this.joinedUpcomingClasses,
  });
  late final List<JoinedUpcomingClasses> joinedUpcomingClasses;



  UserDashboard.fromJson(Map<String, dynamic> json){
    joinedUpcomingClasses = List.from(json['joinedUpcomingClasses']).map((e)=>JoinedUpcomingClasses.fromJson(e)).toList();
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['joinedUpcomingClasses'] = joinedUpcomingClasses.map((e)=>e.toJson()).toList();
    return _data;
  }
}

class JoinedUpcomingClasses {
  JoinedUpcomingClasses({
    required this.id,
    required this.classes,
  });
  late final int id;
  late final Classes classes;

  JoinedUpcomingClasses.fromJson(Map<String, dynamic> json){
    id = json['id'];
    classes = Classes.fromJson(json['classes']);
  }

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

class Classes {
  Classes({
    required this.id,
    required this.name,
    required this.location,
  });
  late final int id;
  late final String name;
  late final String location;

  Classes.fromJson(Map<String, dynamic> json){
    id = json['id'];
    name = json['name'];
    location = json['location'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['id'] = id;
    _data['name'] = name;
    _data['location'] = location;
    return _data;
  }
}

I just want to get the Class name and location in my future builder. In java, we used simply getter Java example userDashboard.getjoinedUpcomingClasses().getclasses().getname(),

but in dart how can I get the values of the name and location of the class?

CodePudding user response:

If you want get these data from api response, try this:

UserDashboard result = UserDashboard.fromJson(jsonDecode(response.body));

and then use it like this:

Text(result.joinedUpcomingClasses[0].classes.name);
  • Related