0

I'm trying to solve an issue where I get the runtime exception:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The getter 'iterator' was called on null.
Receiver: null
Tried calling: iterator
The relevant error-causing widget was: 
  RecordTile AndroidStudioProjects/abc/lib/screens/clinical_records_screen.dart:80:31
════════════════════════════════════════════════════════════════════════════════════════════════════

The exception is in the line:

return loading
  ? LoadingAnimation()
  : RecordTile(
      records: clinical_records,
      position: position,
    );

and is being generated even after I have wrapped it in a try/catch block. How do I get to the root of this? I tried checking whether an element in the list is null.

My code is as follows:

class PreviousRecordsSummaryScreen extends StatefulWidget {
  static const String id = 'ClinicalRecordsScreen';
  List<CheckinNew> clinical_records;
  Customer customer;
  PreviousRecordsSummaryScreen({
    this.clinical_records,
    this.customer,
  });

  @override
  _PreviousRecordsSummaryScreenState createState() =>
      _PreviousRecordsSummaryScreenState();
}

class _PreviousRecordsSummaryScreenState
    extends State<PreviousRecordsSummaryScreen> {
  List<CheckinNew> clinical_records;
  Customer customer;
  bool loading;

  List<CheckinNew> sortedRecords(List<CheckinNew> initialList) {
    print("Sorting by date.. newest first");
    List<CheckinNew> sortList = initialList;
    sortList.sort((b, a) => a.actualDate.compareTo(b.actualDate));
    print(sortList); // [two, four, three]
    return sortList;
  }

  @override
  void initState() {
    clinical_records = widget.clinical_records;
    customer = widget.customer;
    print("Customer: ${customer.name} ${customer.cstid}");
    loading = false;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print("In ClinicalRecordsScreen");
    print("clinical_records is $clinical_records");
    clinical_records = sortedRecords(clinical_records);

    return Scaffold(
      appBar: AppBar(title: Text("${widget.customer.name}'s visits")),
      body: Container(
        child: ListView(
          shrinkWrap: true,
          children: [
            clinical_records == null
                ? Container()
                : ListView.builder(
                    shrinkWrap: true,
                    itemCount: (clinical_records == null)
                        ? 0
                        : clinical_records.length,
                    itemBuilder: (BuildContext context, int position) {
                      print(
                          "Before calling RecordTile, position:$position clinical_records:$clinical_records ");
                      print("Printing each element");
                      int index = 0;
                      for (CheckinNew el in clinical_records) {
                        print("el: $el $index");
                        index++;
                      }
                      try {
                        return loading
                            ? LoadingAnimation()
                            : RecordTile(
                                records: clinical_records,
                                position: position,
                              );
                      } catch (e) {
                        return Container();
                      }
                    },
                  ),
          ],
        ),
      ),
    );
  }
}

class RecordTile extends StatefulWidget {
  RecordTile({
    this.records,
    this.position,
    this.expanded = false,
  });

  List<CheckinNew> records;
  int position;
  bool expanded;

  @override
  _RecordTileState createState() => _RecordTileState();
}

class _RecordTileState extends State<RecordTile> {
  bool expanded;
  List<CheckinNew> records;
  int position;

  @override
  void initState() {
    expanded = widget.expanded;
    records = widget.records;
    position = widget.position;
    super.initState();
  }

  Widget medicines(List<MedsResponse> meds) {
    List<Widget> mylist = [];
    for (MedsResponse presc in meds) {
      print(presc.brand);
      mylist.add(Divider(
        height: 10,
      ));
      mylist.add(
        Wrap(
          alignment: WrapAlignment.start,
          crossAxisAlignment: WrapCrossAlignment.start,
          children: [
            CircleAvatar(
              radius: 10,
              backgroundColor: Colors.grey.shade800,
              child: Text((meds.indexOf(presc) + 1).toString()),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 2),
            ),
            Text(
              presc.brand,
              style: TextStyle(color: Colors.black),
            ),
          ],
        ),
      );
      mylist.add(
        Padding(
          padding: EdgeInsets.symmetric(vertical: 2),
        ),
      );

      mylist.add(
        Row(
          children: [
            Padding(padding: EdgeInsets.symmetric(horizontal: 10)),
            Text(
              '${presc.dose} ${presc.unit} ${presc.freq} x ${presc.durn} ${presc.durnunit}',
              style: TextStyle(color: Colors.black),
            ),
          ],
        ),
      );

      mylist.add(
        Padding(
          padding: EdgeInsets.symmetric(vertical: 2),
        ),
      );

      mylist.add(
        Wrap(
          children: [
            Padding(padding: EdgeInsets.symmetric(horizontal: 10)),
            Text(
              '(${presc.generic})',
              style: TextStyle(
                color: Colors.black,
              ),
            ),
          ],
        ),
      );

      mylist.add(
        Padding(
          padding: EdgeInsets.symmetric(vertical: 2),
        ),
      );

    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: mylist,
    );
  }

  @override
  Widget build(BuildContext context) {
    print("Is expanded");
    return Card(
      child: InkWell(
        onTap: () {
          print("expanded is $expanded");
          setState(() {
            expanded = !expanded;
          });
        },
        child: ListTile(
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                  '${widget.records[widget.position].dateLong()} ${widget.records[widget.position].time}'),
              Text('Checkin #${records[widget.position].checkinno}'),
            ],
          ),
          subtitle: !expanded
              ? Text(
                  records[position].clinicalRecord.diagnosis_as_string(),
                  textAlign: TextAlign.left,
                  style: TextStyle(
                      // color: Colors.white,
                      ),
                )
              : Container(
                  // color: Colors.pink,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(padding: EdgeInsets.symmetric(vertical: 3)),
                      Text(
                        records[position].clinicalRecord.diagnosis_as_string(),
                        textAlign: TextAlign.left,
                        style: TextStyle(
                          color: Colors.black,
                          decorationThickness: 10,
                        ),
                      ),
                      Padding(padding: EdgeInsets.symmetric(vertical: 3)),
                      Text(records[position].clinicalRecord.history),
                      Padding(padding: EdgeInsets.symmetric(vertical: 3)),
                      Text(records[position].clinicalRecord.examination),
                      Padding(padding: EdgeInsets.symmetric(vertical: 3)),
                      Text("Treatment:"),
                      medicines(records[position].prescribedDrugs),
                    ],
                  ),
                ),
        ),
      ),
    );
  }
}
Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86
  • Does this answer your question? [What is a NoSuchMethod error and how do I fix it?](https://stackoverflow.com/questions/64049102/what-is-a-nosuchmethod-error-and-how-do-i-fix-it) – nvoigt Oct 12 '20 at 05:41
  • @nvoigt No, it doesnt. The question is why even after checking for a null value, the exception is thrown. – Joel G Mathew Oct 12 '20 at 13:30
  • Then maybe you need to explain what your problem is in more detail. What *exactly* is `null` and why can't you just check it? – nvoigt Oct 12 '20 at 13:32
  • See the above code please. I have highlighted the line which throws the error, and you can see that I am checking for null value. The exception is not decipherable, and that is why I'm asking it here – Joel G Mathew Oct 12 '20 at 14:09
  • So what *are* the values of `loading`, `clinical_records` and `position` when you put a breakpoint there? – nvoigt Oct 12 '20 at 14:11
  • @nvoigt `loading:false position:43 clinical_records:[Instance of 'CheckinNew',...]` clinical_records is an array of 44 instances of CheckinNew object. – Joel G Mathew Oct 12 '20 at 14:18
  • Then I guess you are looking at the wrong position in your program? Maybe check the RecordTile class? Make it simpler. Does it work when it's just a text printing 'hello'? does it still work when it's a text printing the number of items... you know... debug it, see where the error is. – nvoigt Oct 12 '20 at 14:21

0 Answers0