Home > Software design >  Late Initialization Error in Flutter because of _startDate
Late Initialization Error in Flutter because of _startDate

Time:09-29

As you can see in the included screenshot, I am getting a LateInitializationError upon running my app. The cause is in the code below, but I can't figure out how to fix it. It certainly has to do with the "late DateTime _startDate;" that I am using, but unsure what the right approach is. Do you have any idea? Thanks in advance for looking into it!

class AddEventPage extends StatefulWidget {
  final DateTime? selectedDate;
  final AppEvent? event;

  const AddEventPage({Key? key, this.selectedDate, this.event})
      : super(key: key);
  @override
  _AddEventPageState createState() => _AddEventPageState();
}

late DateTime _startDate;
late TimeOfDay _startTime;
late DateTime _endDate;
late TimeOfDay _endTime;

class _AddEventPageState extends State<AddEventPage> {
  final _formKey = GlobalKey<FormBuilderState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          icon: Icon(
            Icons.clear,
            color: AppColors.primaryColor,
          ),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: ElevatedButton(
              onPressed: () async {
                //save
                _formKey.currentState!.save();
                final data =
                    Map<String, dynamic>.from(_formKey.currentState!.value);
                data["Time Start"] =
                    (data["Time Start"] as DateTime).millisecondsSinceEpoch;
                if (widget.event != null) {
                  //update
                  await eventDBS.updateData(widget.event!.id!, data);
                } else {
                  //create
                  await eventDBS.create({
                    ...data,
                    "user_id": context.read(userRepoProvider).user!.id,
                  });
                }
                Navigator.pop(context);
              },
              child: Text("Save"),
            ),
          )
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(16.0),
        children: <Widget>[
          //add event form
          FormBuilder(
            key: _formKey,
            child: Column(
              children: [
                FormBuilderTextField(
                  name: "title",
                  initialValue: widget.event?.title,
                  decoration: InputDecoration(
                      hintText: "Add Title",
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.only(left: 48.0)),
                ),
                Divider(),
                FormBuilderTextField(
                  name: "description",
                  initialValue: widget.event?.description,
                  minLines: 1,
                  maxLines: 5,
                  decoration: InputDecoration(
                      hintText: "Add Details",
                      border: InputBorder.none,
                      prefixIcon: Icon(Icons.short_text)),
                ),
                Divider(),
                FormBuilderSwitch(
                  name: "public",
                  initialValue: widget.event?.public ?? false,
                  title: Text("Public"),
                  controlAffinity: ListTileControlAffinity.leading,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                  ),
                ),
                Divider(),
                Neumorphic(
                  style: NeumorphicStyle(color: Colors.white),
                  child: Column(
                    children: [
                      GestureDetector(
                          child: Text(
                              DateFormat('EEE, MMM dd, yyyy')
                                  .format(_startDate),
                              textAlign: TextAlign.left),
                          onTap: () async {
                            final DateTime? date = await showDatePicker(
                              context: context,
                              initialDate: _startDate,
                              firstDate: DateTime(2000),
                              lastDate: DateTime(2100),
                            );

                            if (date != null && date != _startDate) {
                              setState(() {
                                final Duration difference =
                                    _endDate.difference(_startDate);
                                _startDate = DateTime(
                                    date.year,
                                    date.month,
                                    date.day,
                                    _startTime.hour,
                                    _startTime.minute,
                                    0);
                                _endDate = _startDate.add(difference);
                                _endTime = TimeOfDay(
                                    hour: _endDate.hour,
                                    minute: _endDate.minute);
                              });
                            }
                          }),
                      Container(
                        child: FormBuilderDateTimePicker(
                          name: "Time End",
                          initialValue: widget.selectedDate ??
                              widget.event?.date ??
                              DateTime.now(),
                          initialDate: DateTime.now(),
                          fieldHintText: "Add Date",
                          initialDatePickerMode: DatePickerMode.day,
                          inputType: InputType.both,
                          format: DateFormat('EEE, dd MMM, yyyy HH:mm'),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            prefix: Text('           '),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Error

CodePudding user response:

late to the keyword means that your property will be initialized when you use it for the first time.

You like to initialize like this:

late DateTime _startDate = DateTime.now();

And as well as change the others value respectively

CodePudding user response:

In GestureDetector you are using a Text widget and passing the _startDate as value but you have not assigned any value to it beforehand, this causes this error, try giving it an initial value before using it.

  • Related