1

I am trying to parse a JSON array to a List in my app, it worked with other model classes but I getting the error with this particular one only. I have used similar codes in other cases it worked but it's not working here. If you use just List instead of changing the type to the model class and initiate the response it works.

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
Class 'StudyList' has no instance method '[]'.
Receiver: Instance of 'StudyList'
Tried calling: []("reportStatus")
════════════════════════════════════════════════════════════════════════════════════════════════════

This is my model class:

class StudyList {
  String studyUID;
  String patientId;
  String patientName;
  String studyDateTime;
  String modalityName;
  String study;
  String studyDescription;
  String refferringPhysician;
  String clinicalHistory;
  String siteName;
  String reportPath;
  String attachmentPath;
  String imageReceviedTime;
  var reportReceviedTime;
  int noOfImages;
  String reportStatus;
  String radiologistName;
  String gender;
  String age;
  int series;
  int siteID;
  int radiologistID;
  var reportReceviedTime1;
  String radiologistAssignedTime;
  int radcentreId;
  String examdate;
  int emergencyst;
  String studycode;
  var repdown;
  String thumbnail;
  int modality;
  int status;
  var studyview;
  var studydown;

  StudyList(
      {this.studyUID,
        this.patientId,
        this.patientName,
        this.studyDateTime,
        this.modalityName,
        this.study,
        this.studyDescription,
        this.refferringPhysician,
        this.clinicalHistory,
        this.siteName,
        this.reportPath,
        this.attachmentPath,
        this.imageReceviedTime,
        this.reportReceviedTime,
        this.noOfImages,
        this.reportStatus,
        this.radiologistName,
        this.gender,
        this.age,
        this.series,
        this.siteID,
        this.radiologistID,
        this.reportReceviedTime1,
        this.radiologistAssignedTime,
        this.radcentreId,
        this.examdate,
        this.emergencyst,
        this.studycode,
        this.repdown,
        this.thumbnail,
        this.modality,
        this.status,
        this.studyview,
        this.studydown});

  StudyList.fromJson(Map<String, dynamic> json) {
    studyUID = json['studyUID'];
    patientId = json['patientId'];
    patientName = json['patientName'];
    studyDateTime = json['studyDateTime'];
    modalityName = json['modalityName'];
    study = json['study'];
    studyDescription = json['studyDescription'];
    refferringPhysician = json['refferringPhysician'];
    clinicalHistory = json['clinicalHistory'];
    siteName = json['siteName'];
    reportPath = json['reportPath'];
    attachmentPath = json['attachmentPath'];
    imageReceviedTime = json['imageReceviedTime'];
    reportReceviedTime = json['reportReceviedTime'];
    noOfImages = json['noOfImages'];
    reportStatus = json['reportStatus'];
    radiologistName = json['radiologistName'];
    gender = json['gender'];
    age = json['age'];
    series = json['series'];
    siteID = json['siteID'];
    radiologistID = json['radiologistID'];
    reportReceviedTime1 = json['reportReceviedTime1'];
    radiologistAssignedTime = json['radiologistAssignedTime'];
    radcentreId = json['radcentreId'];
    examdate = json['examdate'];
    emergencyst = json['emergencyst'];
    studycode = json['studycode'];
    repdown = json['repdown'];
    thumbnail = json['thumbnail'];
    modality = json['modality'];
    status = json['status'];
    studyview = json['studyview'];
    studydown = json['studydown'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['studyUID'] = this.studyUID;
    data['patientId'] = this.patientId;
    data['patientName'] = this.patientName;
    data['studyDateTime'] = this.studyDateTime;
    data['modalityName'] = this.modalityName;
    data['study'] = this.study;
    data['studyDescription'] = this.studyDescription;
    data['refferringPhysician'] = this.refferringPhysician;
    data['clinicalHistory'] = this.clinicalHistory;
    data['siteName'] = this.siteName;
    data['reportPath'] = this.reportPath;
    data['attachmentPath'] = this.attachmentPath;
    data['imageReceviedTime'] = this.imageReceviedTime;
    data['reportReceviedTime'] = this.reportReceviedTime;
    data['noOfImages'] = this.noOfImages;
    data['reportStatus'] = this.reportStatus;
    data['radiologistName'] = this.radiologistName;
    data['gender'] = this.gender;
    data['age'] = this.age;
    data['series'] = this.series;
    data['siteID'] = this.siteID;
    data['radiologistID'] = this.radiologistID;
    data['reportReceviedTime1'] = this.reportReceviedTime1;
    data['radiologistAssignedTime'] = this.radiologistAssignedTime;
    data['radcentreId'] = this.radcentreId;
    data['examdate'] = this.examdate;
    data['emergencyst'] = this.emergencyst;
    data['studycode'] = this.studycode;
    data['repdown'] = this.repdown;
    data['thumbnail'] = this.thumbnail;
    data['modality'] = this.modality;
    data['status'] = this.status;
    data['studyview'] = this.studyview;
    data['studydown'] = this.studydown;
    return data;
  }
}

This is my code for parsing the data from the API:

List<StudyList> _patientDataapi = List();

setState(() {
             _shimmerLoader = true;
           

             _patientDataapi = (json.decode(res.body))
               .map<StudyList>((item) => StudyList.fromJson(item))
               .toList();
             
           });

And lastly, this is the JSON data being fetched while making API:

[
    {
        "studyUID": "1.2.840.113619.2.55.3.2831168001.314.1602949790.991",
        "patientId": "4789",
        "patientName": "MR.ANIKET ADKAKE",
        "studyDateTime": "2020-10-17T22:22:04",
        "modalityName": "CT",
        "study": "NECK PLAIN",
        "studyDescription": "CT-NECK",
        "refferringPhysician": "G.H.S",
        "clinicalHistory": "H/O- LOSS OF VOICE",
        "siteName": "Aditya sangli",
        "reportPath": "",
        "attachmentPath": "",
        "imageReceviedTime": "2020-10-17T22:24:49",
        "reportReceviedTime": null,
        "noOfImages": 215,
        "reportStatus": "Pending",
        "radiologistName": "Dr.Agarwal",
        "gender": "M",
        "age": "026Y",
        "series": 5,
        "siteID": 209,
        "radiologistID": 518,
        "reportReceviedTime1": null,
        "radiologistAssignedTime": "2020-10-17T22:48:00",
        "radcentreId": 6,
        "examdate": "2020-10-17T21:38:57",
        "emergencyst": 0,
        "studycode": "CT-21",
        "repdown": null,
        "thumbnail": "",
        "modality": 1,
        "status": 3,
        "studyview": null,
        "studydown": null
    },
    {
        "studyUID": "1.2.840.113619.2.55.3.2831168001.314.1602949791.126",
        "patientId": "CT-4792",
        "patientName": "MR.ANIKET ADAKE",
        "studyDateTime": "2020-10-17T23:49:32",
        "modalityName": "CT",
        "study": "NECK PLAIN",
        "studyDescription": "CT-NECK PLAIN",
        "refferringPhysician": "G.H.S",
        "clinicalHistory": "H/O- LOSS OF VOICE",
        "siteName": "Aditya sangli",
        "reportPath": "C:\\KINSOLUTIONS\\Team\\Report\\1.2.840.113619.2.55.3.2831168001.314.1602949791.126.docx",
        "attachmentPath": "",
        "imageReceviedTime": "2020-10-17T23:50:29",
        "reportReceviedTime": null,
        "noOfImages": 273,
        "reportStatus": "Final",
        "radiologistName": "Dr.Agarwal",
        "gender": "M",
        "age": "025Y",
        "series": 4,
        "siteID": 209,
        "radiologistID": 518,
        "reportReceviedTime1": "2020-10-18T00:25:07",
        "radiologistAssignedTime": "2020-10-17T23:52:08",
        "radcentreId": 6,
        "examdate": "2020-10-17T23:46:03",
        "emergencyst": 0,
        "studycode": "CT-21",
        "repdown": true,
        "thumbnail": "",
        "modality": 1,
        "status": 5,
        "studyview": null,
        "studydown": null
    }
]

2 Answers2

0

So this is the json that you provided:

[
    {
        "studyUID": "1.2.840.113619.2.55.3.2831168001.314.1602949790.991",
        "patientId": "4789",
        "patientName": "MR.ANIKET ADKAKE",
        "studyDateTime": "2020-10-17T22:22:04",
        "modalityName": "CT",
        "study": "NECK PLAIN",
        "studyDescription": "CT-NECK",
        "refferringPhysician": "G.H.S",
        "clinicalHistory": "H/O- LOSS OF VOICE",
        "siteName": "Aditya sangli",
        "reportPath": "",
        "attachmentPath": "",
        "imageReceviedTime": "2020-10-17T22:24:49",
        "reportReceviedTime": null,
        "noOfImages": 215,
        "reportStatus": "Pending",
        "radiologistName": "Dr.Agarwal",
        "gender": "M",
        "age": "026Y",
        "series": 5,
        "siteID": 209,
        "radiologistID": 518,
        "reportReceviedTime1": null,
        "radiologistAssignedTime": "2020-10-17T22:48:00",
        "radcentreId": 6,
        "examdate": "2020-10-17T21:38:57",
        "emergencyst": 0,
        "studycode": "CT-21",
        "repdown": null,
        "thumbnail": "",
        "modality": 1,
        "status": 3,
        "studyview": null,
        "studydown": null
    },
    {
        "studyUID": "1.2.840.113619.2.55.3.2831168001.314.1602949791.126",
        "patientId": "CT-4792",
        "patientName": "MR.ANIKET ADAKE",
        "studyDateTime": "2020-10-17T23:49:32",
        "modalityName": "CT",
        "study": "NECK PLAIN",
        "studyDescription": "CT-NECK PLAIN",
        "refferringPhysician": "G.H.S",
        "clinicalHistory": "H/O- LOSS OF VOICE",
        "siteName": "Aditya sangli",
        "reportPath": "C:\\KINSOLUTIONS\\Team\\Report\\1.2.840.113619.2.55.3.2831168001.314.1602949791.126.docx",
        "attachmentPath": "",
        "imageReceviedTime": "2020-10-17T23:50:29",
        "reportReceviedTime": null,
        "noOfImages": 273,
        "reportStatus": "Final",
        "radiologistName": "Dr.Agarwal",
        "gender": "M",
        "age": "025Y",
        "series": 4,
        "siteID": 209,
        "radiologistID": 518,
        "reportReceviedTime1": "2020-10-18T00:25:07",
        "radiologistAssignedTime": "2020-10-17T23:52:08",
        "radcentreId": 6,
        "examdate": "2020-10-17T23:46:03",
        "emergencyst": 0,
        "studycode": "CT-21",
        "repdown": true,
        "thumbnail": "",
        "modality": 1,
        "status": 5,
        "studyview": null,
        "studydown": null
    }
]

This is the updated model class for the above json :

// To parse this JSON data, do
//
//     final studyList = studyListFromJson(jsonString);

import 'dart:convert';

List<StudyList> studyListFromJson(String str) => List<StudyList>.from(json.decode(str).map((x) => StudyList.fromJson(x)));

String studyListToJson(List<StudyList> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class StudyList {
    StudyList({
        this.studyUid,
        this.patientId,
        this.patientName,
        this.studyDateTime,
        this.modalityName,
        this.study,
        this.studyDescription,
        this.refferringPhysician,
        this.clinicalHistory,
        this.siteName,
        this.reportPath,
        this.attachmentPath,
        this.imageReceviedTime,
        this.reportReceviedTime,
        this.noOfImages,
        this.reportStatus,
        this.radiologistName,
        this.gender,
        this.age,
        this.series,
        this.siteId,
        this.radiologistId,
        this.reportReceviedTime1,
        this.radiologistAssignedTime,
        this.radcentreId,
        this.examdate,
        this.emergencyst,
        this.studycode,
        this.repdown,
        this.thumbnail,
        this.modality,
        this.status,
        this.studyview,
        this.studydown,
    });

    String studyUid;
    String patientId;
    String patientName;
    DateTime studyDateTime;
    String modalityName;
    String study;
    String studyDescription;
    String refferringPhysician;
    String clinicalHistory;
    String siteName;
    String reportPath;
    String attachmentPath;
    DateTime imageReceviedTime;
    dynamic reportReceviedTime;
    int noOfImages;
    String reportStatus;
    String radiologistName;
    String gender;
    String age;
    int series;
    int siteId;
    int radiologistId;
    DateTime reportReceviedTime1;
    DateTime radiologistAssignedTime;
    int radcentreId;
    DateTime examdate;
    int emergencyst;
    String studycode;
    bool repdown;
    String thumbnail;
    int modality;
    int status;
    dynamic studyview;
    dynamic studydown;

    factory StudyList.fromJson(Map<String, dynamic> json) => StudyList(
        studyUid: json["studyUID"],
        patientId: json["patientId"],
        patientName: json["patientName"],
        studyDateTime: DateTime.parse(json["studyDateTime"]),
        modalityName: json["modalityName"],
        study: json["study"],
        studyDescription: json["studyDescription"],
        refferringPhysician: json["refferringPhysician"],
        clinicalHistory: json["clinicalHistory"],
        siteName: json["siteName"],
        reportPath: json["reportPath"],
        attachmentPath: json["attachmentPath"],
        imageReceviedTime: DateTime.parse(json["imageReceviedTime"]),
        reportReceviedTime: json["reportReceviedTime"],
        noOfImages: json["noOfImages"],
        reportStatus: json["reportStatus"],
        radiologistName: json["radiologistName"],
        gender: json["gender"],
        age: json["age"],
        series: json["series"],
        siteId: json["siteID"],
        radiologistId: json["radiologistID"],
        reportReceviedTime1: json["reportReceviedTime1"] == null ? null : DateTime.parse(json["reportReceviedTime1"]),
        radiologistAssignedTime: DateTime.parse(json["radiologistAssignedTime"]),
        radcentreId: json["radcentreId"],
        examdate: DateTime.parse(json["examdate"]),
        emergencyst: json["emergencyst"],
        studycode: json["studycode"],
        repdown: json["repdown"] == null ? null : json["repdown"],
        thumbnail: json["thumbnail"],
        modality: json["modality"],
        status: json["status"],
        studyview: json["studyview"],
        studydown: json["studydown"],
    );

    Map<String, dynamic> toJson() => {
        "studyUID": studyUid,
        "patientId": patientId,
        "patientName": patientName,
        "studyDateTime": studyDateTime.toIso8601String(),
        "modalityName": modalityName,
        "study": study,
        "studyDescription": studyDescription,
        "refferringPhysician": refferringPhysician,
        "clinicalHistory": clinicalHistory,
        "siteName": siteName,
        "reportPath": reportPath,
        "attachmentPath": attachmentPath,
        "imageReceviedTime": imageReceviedTime.toIso8601String(),
        "reportReceviedTime": reportReceviedTime,
        "noOfImages": noOfImages,
        "reportStatus": reportStatus,
        "radiologistName": radiologistName,
        "gender": gender,
        "age": age,
        "series": series,
        "siteID": siteId,
        "radiologistID": radiologistId,
        "reportReceviedTime1": reportReceviedTime1 == null ? null : reportReceviedTime1.toIso8601String(),
        "radiologistAssignedTime": radiologistAssignedTime.toIso8601String(),
        "radcentreId": radcentreId,
        "examdate": examdate.toIso8601String(),
        "emergencyst": emergencyst,
        "studycode": studycode,
        "repdown": repdown == null ? null : repdown,
        "thumbnail": thumbnail,
        "modality": modality,
        "status": status,
        "studyview": studyview,
        "studydown": studydown,
    };
}

This is the implementation for:

import 'package:flutter/material.dart';
import 'package:json_parsing_example/model2.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SampleApp(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class SampleApp extends StatefulWidget {
  @override
  _SampleAppState createState() => _SampleAppState();
}

class _SampleAppState extends State<SampleApp> {
  bool _isLoading = false;
  List<StudyList> list = List();

  fetchData() async {
    setState(() {
      _isLoading = true;
    });

    String data =
        await DefaultAssetBundle.of(context).loadString("json/parse.json");

    // This is the above where you get the remote data
    // Like var response = await http.get('your url');
    //  final studyList = studyListFromJson(data);

    final studyList = studyListFromJson(data);

    list = studyList;

    setState(() {
      _isLoading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Your heading'),
        ),
        body: Container(
            child: _isLoading
                ? Center(child: CircularProgressIndicator())
                : Column(
                    children: <Widget>[
                      ListView.builder(
                        shrinkWrap: true,
                          itemCount: list.length,
                          itemBuilder: (context, index) {
                            return Card(
                              child: Column(
                                children: <Widget>[
                                  Text('${list[index].patientId }'),
                                  Text('${list[index].patientName}')
                                ],
                              ),
                            );
                          })
                    ],
                  )));
  }
}

Let me know if it works.

Sagar Acharya
  • 3,397
  • 4
  • 12
  • 34
  • I tried final studyList = studyListFromJson(json.decode(res.body)); _patientDataapi = studyList; but getting error type 'List' is not a subtype of type 'String' – Ayan Bhattacharjee Oct 29 '20 at 06:04
  • Can you edit your code so that it would be better for understanding – Sagar Acharya Oct 29 '20 at 06:08
  • I copied the model class just as you posted – Ayan Bhattacharjee Oct 29 '20 at 06:16
  • studyListFromJson(json.decode(res.body)); don't do this you, should just do this studyListFromJson(res.body); check out and let me know if it works – Sagar Acharya Oct 29 '20 at 06:29
  • you just need to pass the res.body to the studyListFromJson(res.body) the conversion is done inside the model class . – Sagar Acharya Oct 29 '20 at 06:32
  • final studyList = studyListFromJson(res.body); _patientDataapi = studyList; like this right but this generates the same error ════════ Exception caught by widgets library ═══════════════════════════════════════════════════════ Class 'StudyList' has no instance method '[]'. Receiver: Instance of 'StudyList' Tried calling: []("reportStatus") ════════════════════════════════════════════════════════════════════════════════════════════════════ – Ayan Bhattacharjee Oct 29 '20 at 06:35
  • Here is the code: if(resBodystudyNames.toString().length>2) { try { setState(() { _shimmerLoader = true; final studyList = studyListFromJson(res.body); _patientDataapi = studyList; }); } catch (e){ //print exception print(e); } } – Ayan Bhattacharjee Oct 29 '20 at 06:38
  • not this one the one where in the ui that you are assigning the data. – Sagar Acharya Oct 29 '20 at 06:39
  • Here is the code: var res = await http.get(uri); if(resBodystudyNames.toString().length>2) { try { setState(() { _shimmerLoader = true; final studyList = studyListFromJson(res.body); _patientDataapi = studyList; }); } catch (e){ //print exception print(e); } } – Ayan Bhattacharjee Oct 29 '20 at 06:40
  • are you checking if the response that you are fetching is 200 . just check it using the print(res.statusCode); – Sagar Acharya Oct 29 '20 at 06:50
  • if(res.statusCode==201) { if(resBodystudyNames.toString().length>2) { try { setState(() { _shimmerLoader = true; final studyList = studyListFromJson(res.body); _patientDataapi = studyList; }); } catch (e){ print(e); } } else { showErrorToast("Sorry No Data Avialable", context); setState(() { _shimmerLoader = true; }); } } – Ayan Bhattacharjee Oct 29 '20 at 06:52
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/223798/discussion-between-sagar-acharya-and-ayan-bhattacharjee). – Sagar Acharya Oct 29 '20 at 07:00
  • What was the issue by the way – Sagar Acharya Nov 03 '20 at 16:29
  • text: '${data.patientName}', //${data['patientName']} – Ayan Bhattacharjee Nov 04 '20 at 05:13
0

Here is the solution:

API call:

  filteredUsers = (resBodystudyNames)
            .map<StudyList>((item) => StudyList.fromJson(item))
            .toList();
    
     _patientDataapi=filteredUsers;

List View:

   child: ListView.builder(
                          
                            itemCount: _patientDataapi.length,
                            itemBuilder: (context, index) {
                              return Container(
                                padding: EdgeInsets.fromLTRB(4, 0, 5, 0),
                                height: 185,
                                width: double.maxFinite,
                                child: Card(
                                  shape: RoundedRectangleBorder(
                                    borderRadius:
                                        BorderRadius.circular(20.0),
                                  ),
                                  elevation: 5,
                                  child: Container(
                                    height: 2.0,
                                    decoration: BoxDecoration(
                                      border: Border(
                                        left: _cardborderColor(
                                            _patientDataapi[index]),
                                      ),
                                      color: Colors.white,
                                    ),
                                    child: Padding(
                                      padding: EdgeInsets.all(5),
                                      child: Stack(children: <Widget>[
                                        Align(
                                          alignment: Alignment.centerRight,
                                          child: Stack(
                                            children: <Widget>[
                                              Padding(
                                                  padding:
                                                      const EdgeInsets.only(
                                                          left: 10, top: 2),
                                                  child: Column(
                                                    children: <Widget>[
                                                      Row(
                                                        children: <Widget>[
                                                          Wrap(
                                                            children: [
                                                              patient_Name(
                                                                  _patientDataapi[
                                                                      index]),
                                                              SizedBox(
                                                                width: 20,
                                                              ),
                                                              _patientAgeSex(
                                                                  _patientDataapi[
                                                                      index])
                                                            ],
                                                          ),
                                                        ],
                                                      ),
                                                      SizedBox(
                                                        height: 5,
                                                      ),
                                                      Row(
                                                        children: [
                                                          Flexible(
                                                            flex: 0,
                                                            child: patientReport(
                                                                _patientDataapi[
                                                                    index]),
                                                          ),
                                                          SizedBox(
                                                            width: 40,
                                                          ),
                                                          Flexible(
                                                            flex: 2,
                                                            child: patientStudyName(
                                                                _patientDataapi[
                                                                    index]),
                                                          ),
                                                          Flexible(
                                                            flex: 2,
                                                            child: patientSeeBar(
                                                                _patientDataapi[
                                                                    index]),
                                                          ),
                                                        ],
                                                      ),
                                                      SizedBox(
                                                        height: 5,
                                                      ),
                                                      Row(
                                                        children: [
                                                          patientEditInfo(
                                                              _patientDataapi[
                                                                  index]),
                                                          Spacer(),
                                                          moreInfo(
                                                              _patientDataapi[
                                                                  index])
                                                        ],
                                                      ),
                                                      Row(
                                                        children: [
                                                          patientStat(
                                                              _patientDataapi[
                                                                  index]),
                                                          SizedBox(
                                                            width: 20,
                                                          ),
                                                          _patientStat(
                                                              _patientDataapi[
                                                                  index]),
                                                          SizedBox(
                                                            width: 20,
                                                          ),
                                                          patientDoctor(
                                                              _patientDataapi[
                                                                  index]),
                                                        ],
                                                      ),
                                                      Row(
                                                        children: [
                                                          /*patientidData(
                                                  patientData[index])*/
                                                        ],
                                                   
                                                    ],
                                                  ))
                                            ],
                                          ),
                                        )
                                      ]),
                                    ),
                                  ),
                                ),
                              );
                            }),

Widget function:

      Widget patient_Name(var data) {
    return Align(
      alignment: Alignment.centerLeft,
      child: RichText(
        text: TextSpan(
          text: '${data.patientName}', //${data['patientName']}
          style: TextStyle(
              fontWeight: FontWeight.bold, color: Colors.black, fontSize: 14),
          children: <TextSpan>[],
        ),
      ),
    );
  }