0
votes

I'm receiving the following error while trying to display a user's all appointments with their corresponding date and title from databse. Can anyone please point out how to fix it?(Solved!)

Issue: Why there is no list records returning in this flutter code application?

Here is the code:

import 'package:flutter/material.dart';
import 'package:frontend/main.dart';
import 'package:frontend/util/authentication.dart';
import 'package:frontend/util/serverDetails.dart';
import 'package:http/http.dart' as http;
import 'package:frontend/components/appointment.dart';
import 'package:frontend/screens/appointmentdetail.dart';
import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:frontend/screens/appointments.dart';
import 'package:table_calendar/table_calendar.dart';

class AppointmentList extends StatefulWidget {
  @override
  _AppointmentListState createState() => _AppointmentListState();
}

class _AppointmentListState extends State<AppointmentList>
    with TickerProviderStateMixin {
  Map<DateTime, List> _events;
  List _selectedEvents;

  @override
  void initState() {
    super.initState();
    _events = Map<DateTime, List>();
    getAppointments();
  }

  getAppointments() async {
    String currentToken = await Authentication.getCurrentToken();
    print(currentToken);
    if (currentToken == null) {
      print('bouncing');
      Authentication.bounceUser(context);
    } else {
      String auth = "Bearer " + currentToken;
      String url = ServerDetails.ip +
          ':' +
          ServerDetails.port +
          ServerDetails.api +
          'me/appointments';
      print(url);
      Map<String, String> headers = {"Authorization": auth};
      print(headers);
      var jsonResponse = null;
      var response = await http.get(url, headers: headers);
      print(response.body);
      if (response.statusCode == 200) {
        print("200" + response.body);
        jsonResponse = json.decode(response.body);
        if (jsonResponse != null) {
          setState(() {
            for (var doc in jsonResponse) {
              Appointment temp = Appointment.fromJson(doc);
              print("TEMP" + temp.date.toString());
              //print("TEMP" + temp.duration.toString());
              if (_events[temp.date] == null) {
                print("deb1" + temp.date.toString());
                _events[temp.date] = List()..add(temp);
              } else {
                //_events[temp.date] = List()..add(temp);
                _events[temp.date].add(temp);
              }
            }
          });
        }
      } else {
        print(response.body);
      }
    }
  }

  void _allDataSelected(DateTime day, List events) {
    print('CALLBACK: _allDaySelected');
    setState(() {
      _selectedEvents = events;
    });
  }

  @override
  build(context) {
    return Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(60.0),
          child: AppBar(
            leading: new IconButton(
                icon: new Icon(Icons.arrow_back),
                color: Colors.black,
                onPressed: () {
                  setState(() {});
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => MainPage()));
                }),
            centerTitle: true,
            title: Text("Appointment", style: TextStyle(color: Colors.black)),
            backgroundColor: Colors.white,
            brightness: Brightness.light,
//          backgroundColor: Color(0x44000000),
            elevation: 0.5,
            actions: <Widget>[
              IconButton(
                color: Colors.black,
                icon: Icon(Icons.calendar_view_day),
                onPressed: () {
                  setState(() {});
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => Appointments()));
                },
              )
            ],
          ),
        ),
        body: ListView(
            children: _selectedEvents
                .map((event) => Container(
                    decoration: BoxDecoration(
                      border: Border.all(width: 0.8),
                      borderRadius: BorderRadius.circular(12.0),
                    ),
                    margin: const EdgeInsets.symmetric(
                        horizontal: 8.0, vertical: 4.0),
                    child: (event is Appointment)
                        ? ListTile(
                            leading: Column(children: <Widget>[
                              //Show Weekday, Month and day of Appiontment
                              Text(
                                  DateFormat('EE').format(event.date) +
                                      '  ' +
                                      DateFormat.MMMd().format(event.date),
                                  style: TextStyle(
                                    color: Colors.blue.withOpacity(1.0),
                                    fontWeight: FontWeight.bold,
                                  )),
                              //Show Start Time of Appointment
                              Text(DateFormat.jm().format(event.date),
                                  textAlign: TextAlign.center,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    height: 1.5,
                                  )),
                              //Show End Time of Appointment
                              Text(
                                DateFormat.jm().format(event.date.add(
                                    Duration(minutes: event.duration ?? 0))),
                                style: TextStyle(
                                    color: Colors.black.withOpacity(0.6)),
                              ),
                            ]), //Text(DateFormat.Hm().format(event.date)),//DateFormat.Hm().format(now)
                            title: Text(event.title),
                            trailing: event.status == 'UNCONFIRMED'
                                ? Column(children: <Widget>[
                                    //event.status=='CONFIRMED' ?
                                    Icon(Icons.error,
                                        color: Colors.pink,
                                        //size:25.0,
                                        semanticLabel:
                                            'Unconfirmed Appointment'), //:Container(width:0,height:0),
                                    Icon(Icons.arrow_right),
                                  ])
                                : Icon(Icons.arrow_right),
                            onTap: () {
                              setState(() {});
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          AppointmentDetail(event)));
                            },
                          )
                        : null))
                .toList()));
  }
}

Another part of code for appointment.dart, which shows how that appointment looks like:

import 'package:flutter/foundation.dart';

class Appointment {
  final String id;
  final String pid;
  final String title;
  final String detail;
  final DateTime date;
  final int duration;
  final String note;
  final String userNote;
  final String status;

  var doctor;

  Appointment(
      {this.id,
      this.pid,
      this.title,
      this.detail,
      this.date,
      this.duration,
      this.note,
      this.userNote,
      this.status});

  factory Appointment.fromJson(Map<String, dynamic> json) {
    return Appointment(
        id: json['id'],
        pid: json['uid'],
        title: json['title'],
        detail: json['detail'],
        date: DateTime.parse(json['date']),
        duration: json['duration'] as int,
        note: json['note'],
        userNote: json['user_note'],
        status: json['status']);
  }
}

Here is the expected outcomes: enter image description here

Here is the new outcomes: (should have the expected outcomes below the 'Appointment'title) enter image description here

Here is the update code:

  @override
  void initState() {
    super.initState();
    _events = Map<DateTime, List>();
    getAppointments().then((result) {
      print("result:$result");
      setState(() {});
    });
  }

Here is the console output: enter image description here

1

1 Answers

0
votes

In your code _selectedEvents is null, it is not initialized. Code which uses the _selectedEvents variable is _allDataSelected() method which isn't called.

It's a good practice to initialize the variables like this:

List _selectedEvents = [];