Search code examples
jsonflutterapidartmodel

How to store complex json data in model class in flutter


Here is my code

I've tried printing values. I got value in the token. I'm able to iterate through each value present in API using for each loop but data isn't stored in my model class.

    SharedPreferences prefs = await SharedPreferences.getInstance();
    final token = prefs.getString("token") ?? null;
    final userId = prefs.getInt("id") ?? null;
    List<GroupListData> grpDataList = [];
    if (token != null) {
      String url = "${NetworkRequest.baseUrl}/api/group_list";
      var groupRes = await http.post(Uri.parse(url), body: {
        "user_id": '$userId'
      }, headers: {
        //'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer $token',
      });
      //print(groupRes.body);
      if (groupRes.statusCode == 200) {
        final rowJsonData = jsonDecode(groupRes.body);

        GroupListData groupListData;
        List<dynamic> groupLists = rowJsonData['data'];
        groupLists.forEach((d) {
          print(d['id']);

          groupListData = GroupListData(
            id: d['id'],
            groupName: d["groupName"],
            status: d["status"],
            createdAt: d["createdAt"],
            updatedAt: d["updatedAt"],
          );
          grpDataList.add(groupListData);
        });

        for (var d in rowJsonData['data']) {
          print(d);
        }
      } else {
        print('grpResp ${groupRes.statusCode}');
      }
      //print('Token : $token');

    } else {
      print('token is empty');
    }
    print(grpDataList);
    return grpDataList;
  }

here is my JSON Data

{
    "data": [
        {
            "id": 1,
            "group_name": "payroll",
            "status": 1,
            "created_at": "2021-07-20 08:27:31",
            "updated_at": "2021-07-20 10:09:11"
        },
        {
            "id": 2,
            "group_name": "New Recruitment",
            "status": 1,
            "created_at": "2021-07-20 11:21:40",
            "updated_at": "2021-07-20 11:21:40"
        }
    ],
    "message": "Data Found",
    "status": 200
}

Here is my model class I think that there is an issue in my model class I am not able to understand


class GroupListData {
  GroupListData({
     this.id,
     this.groupName,
     this.status,
     this.createdAt,
     this.updatedAt,
  });

  int? id;
  String? groupName;
  int? status;
  DateTime? createdAt;
  DateTime? updatedAt;

  factory GroupListData.fromJson(Map<String, dynamic> json) => GroupListData(
        id: json["id"],
        groupName: json["group_name"],
        status: json["status"],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "group_name": groupName,
        "status": status,
        "created_at": createdAt!.toIso8601String(),
        "updated_at": updatedAt!.toIso8601String(),
      };
}


Here is my UI code

     FutureBuilder<List<GroupListData>>(
          future: getGroupListData(),
          builder: (BuildContext context,
              AsyncSnapshot<List<GroupListData>> snapshot) {
            if (snapshot.data == null) {
              return Container(
                child: Center(
                  child: Text('Loading...'),
                ),
              );
            }
            return ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: snapshot.data!.length,
                itemBuilder: (BuildContext context, int index) {
                  return RoundedCard(
                      str: '${snapshot.data![index].groupName}',   ///.groupName always return null value
                      onTap: () {
                        Navigator.push(
                          context,
                          PageTransition(
                              type: PageTransitionType.rightToLeft,
                              child: FeedPage(feedTitle: 'Marketing Team'),
                              inheritTheme: true,
                              ctx: context),
                        );
                        print('Marketing card');
                      });
                });
          },
        ),

thanks in advance


Solution

  • You dont need to convert your json to modal by yourself.

    1. if the Flutter SDK < 2.0 (Null safety) then please use this online json converter https://javiercbk.github.io/json_to_dart/

    2. otherwise use this online json Converter for Flutter > 2.0 https://app.quicktype.io/