The method ‘changeeventdescription’ was called on null

I have looked at many answers to other questions but I think I am missing something still. I am developing a flutter app and the page that I am having trouble with is a page where I create meetings for a calendar.

When I look at the debug log I see that the eventProvider is null. I copied the structure from another screen in my app and everything works fine there. What have I missed?

Here is the code from the screen:

    final eventRef = FirebaseFirestore.instance.collection(('events'));

class AddEventScreen extends StatefulWidget {
  static const String id = 'add_event_screen';
  final Event event;

  AddEventScreen([this.event]);

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

class _AddEventScreenState extends State<AddEventScreen> {
  final _db = FirebaseFirestore.instance;

  final eventNameController = TextEditingController();
  final eventStartTimeController = TextEditingController();
  final eventDurationController = TextEditingController();
  final eventDateController = TextEditingController();
  final eventDescriptionController = TextEditingController();

  @override
  void dispose() {
    eventNameController.dispose();
    eventStartTimeController.dispose();
    eventDurationController.dispose();
    eventDateController.dispose();
    eventDescriptionController.dispose();

    super.dispose();
  }

  bool showSpinner = false;
  String eventName;
  String eventStartTime;
  String eventDuration;
  String eventData;
  String eventDescription;


  getCurentAgencyEvents() async {

    if (globals.agencyId == null) {
      eventNameController.text = "";
      eventStartTimeController.text = "";
      eventDurationController.text = "";
      eventDateController.text = "";
      eventDescriptionController.text = "";

    } else {
      final DocumentSnapshot currentEvent =
      await eventRef.doc(globals.agencyId).get();

      // existing record
      // Updates Controllers
      eventNameController.text = currentEvent.data()["name"];
      eventStartTimeController.text = currentEvent.data()['address1'];
      eventDurationController.text = currentEvent.data()['address2'];
      eventDateController.text = currentEvent.data()['city'];
      eventDescriptionController.text = currentEvent.data()['state'];

      // Updates State
      new Future.delayed(Duration.zero, () {
        final eventProvider =
        Provider.of<EventProvider>(context, listen: false);
        eventProvider.loadValues(widget.event);
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    final eventProvider = Provider.of<EventProvider>(context);
    final _firestoreService = FirestoreService();
    DateTime _date = new DateTime.now();
    TimeOfDay _time = new TimeOfDay.now();
    Duration initialtimer = new Duration();
    DateTime _selectedDate = DateTime.now();
    TimeOfDay _timePicked = TimeOfDay.now();
    

    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/Appbar_logo.png',
                fit: BoxFit.cover, height: 56),
          ],
        ),
      ),
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              children: <Widget>[
                Text(
                  'Event Editor',
                  style: TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.w800,
                  ),
                ),
                SizedBox(
                  height: 30.0,
                ),
                TextField(
                  controller: eventNameController,
                  keyboardType: TextInputType.text,
                  textAlign: TextAlign.center,
                  onChanged: (value) {
                    eventProvider.changeeventname(value);
                  },
                  decoration: kTextFieldDecoration.copyWith(
                      hintText: 'Event Name', labelText: 'Event Name'),
                ),
                SizedBox(
                  height: 8.0,
                ),
                TextField(
                  controller: eventDurationController,
                  textAlign: TextAlign.center,
                  onChanged: (value) {
                    eventProvider.changeeventduration(value);
                  },
                  decoration: kTextFieldDecoration.copyWith(
                      hintText: 'Duration', labelText: 'Duration'),
                ),
                SizedBox(
                  height: 8.0,
                ),
                TextField(
                  controller: eventDateController,
                  keyboardType: TextInputType.datetime,
                  textAlign: TextAlign.center,
                    onTap: () async {
                      DateTime _datePicked = await showDatePicker(
                          context: context,
                          initialDate: _selectedDate,
                          //firstDate: new DateTime.now().add(Duration(days: -365)),
                          firstDate: new DateTime(2020),
                          lastDate: new DateTime(2022));
                      if (_date != null && _date != _datePicked) {
                        setState(() {
                          eventDateController.text =
                              DateFormat("MM/dd/yyyy").format(_datePicked);
                          eventProvider.changeeventdate(_datePicked);
                          _selectedDate = _datePicked;
                          //DateFormat("MM/dd/yyyy").format(_date));
                        });
                      }
                    },
                    onChanged: (value) {
                      eventProvider.changeeventdate(_date);
                    },
                    decoration: kTextFieldDecoration.copyWith(
                      hintText: 'Date',
                      labelText: 'Date',
                    ),
                ),
                SizedBox(
                  height: 8.0,
                ),
                TextField(
                  controller: eventStartTimeController,
                  keyboardType: TextInputType.text,
                  textAlign: TextAlign.center,
                  onTap: () async {
                    TimeOfDay _timePicked = await showTimePicker(
                        context: context,
                        initialTime: new TimeOfDay.now());
                    //if (_timePicked != null) {
                      setState(() {
                        eventStartTimeController.text = _timePicked.format(context);
                      });
                    //}
                  },
                  onChanged: (value) {
                    eventProvider.changeeventstarttime(_timePicked);
                  },
                  decoration: kTextFieldDecoration.copyWith(
                    hintText: 'Start Time',
                    labelText: 'Start Time',
                  ),
                ),
                SizedBox(
                  height: 8.0,
                ),
                TextField(
                  controller: eventDescriptionController,
                  keyboardType: TextInputType.text,
                  textAlign: TextAlign.center,
                  onChanged: (value) {
                    eventProvider.changeeventdescription(value);
                  },
                  decoration: kTextFieldDecoration.copyWith(
                      hintText: 'Description', labelText: 'Description'),
                ),
                SizedBox(
                  height: 8.0,
                ),
                RoundedButton(
                  title: 'Save Event',
                  colour: Colors.blueAccent,
                  onPressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      globals.newEvent = true;

                      eventProvider.saveEvent();
                      Navigator.of(context).pushReplacement(MaterialPageRoute(
                          builder: (context) => AppointmentCalendarScreen()));

                      setState(() {
                        showSpinner = false;
                      });
                    } catch (e) {
                      // todo: add better error handling
                      print(e);
                    }
                  },
                ),
                SizedBox(
                  height: 8.0,
                ),
                (widget != null)
                    ? RoundedButton(
                  title: 'Delete',
                  colour: Colors.red,
                  onPressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      //agencyProvider.deleteAgency(globals.currentUid);
                      Navigator.of(context).pushReplacement(MaterialPageRoute(
                          builder: (context) => AppointmentCalendarScreen()));

                      setState(() {
                        showSpinner = false;
                      });
                    } catch (e) {
                      // todo: add better error handling
                      print(e);
                    }
                  },
                )
                    : Container()
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Here is the debug log and I get the same message for each input control:

======== Exception caught by widgets ===============================================================
The following NoSuchMethodError was thrown while calling onChanged:
The method 'changeeventname' was called on null.
Receiver: null
Tried calling: changeeventname("Test event")

Here is the code for the EventProvider:

    class EventProvider with ChangeNotifier {
  final firestoreService = FirestoreService();
  FirebaseFirestore _db = FirebaseFirestore.instance;
  final eventRef = FirebaseFirestore.instance.collection(('events'));

  String _eventName;
  TimeOfDay _eventStartTime;
  String _eventDuration;
  DateTime _eventDate;
  String _eventDescription;

  //Getters
  String get eventName => _eventName;
  TimeOfDay get eventStartTime => _eventStartTime;
  String get eventDuration => _eventDuration;
  DateTime get eventDate => _eventDate;
  String get eventDescription => _eventDescription;

  final EventProvider eventProvider = new EventProvider();

  //Setters

  changeeventname(String value) {
    _eventName = value;
    notifyListeners();
  }

  changeeventstarttime(TimeOfDay value) {
    _eventStartTime = value;
    notifyListeners();
  }

  changeeventduration(String value) {
    _eventDuration = value;
    notifyListeners();
  }

  changeeventdate(DateTime value) {
    _eventDate = value;
    notifyListeners();
  }

  changeeventdescription(String value) {
    _eventDescription = value;
    notifyListeners();
  }

  loadValues(Event event) {
    _eventName = event.eventName;
    _eventStartTime = event.eventStartTime;
    _eventDuration = event.eventDuration;
    _eventDate = event.eventDate;
    _eventDescription = event.eventDescription;
  }

  saveEvent() {

    var newEvent = Event(
        eventName: _eventName,
        eventStartTime: _eventStartTime,
        eventDuration: _eventDuration,
        eventDate: _eventDate,
        eventDescription: _eventDescription);


    // If the agency is a new agency retrieve the agency
    // document ID and save it to a new agent document
    if (globals.newEvent == true) {
      String id = _db.collection('event').doc().id;
      globals.agencyId = id;
      //firestoreService.saveNewEvent(newEvent);
      eventProvider.saveEvent();
      globals.newEvent = false;
    } else {
      firestoreService.saveEvent(newEvent);
    }
  }
}


Read more here: https://stackoverflow.com/questions/67939854/the-method-changeeventdescription-was-called-on-null

Content Attribution

This content was originally published by LostTexan at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: