由于_startDate导致的Flutter延迟初始化错误

3duebb1j  于 2022-12-19  发布在  Flutter
关注(0)|答案(4)|浏览(142)

正如你所看到的截图,我得到了一个LateInitializationError在运行我的应用程序。原因是在下面的代码,但我不知道如何修复它。它肯定与“late DateTime _startDate;“我正在使用,但不确定什么是正确的方法。你有什么想法吗?提前感谢你的调查!

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('           '),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

2ic8powd

2ic8powd1#

late添加到关键字表示属性将在首次使用时初始化。
你喜欢这样初始化:

late DateTime _startDate = DateTime.now();

以及分别更改其他值

jpfvwuh4

jpfvwuh42#

GestureDetector中,您正在使用Text小工具并将_startDate作为值传递,但您事先没有为它分配任何值,这会导致此错误,请尝试在使用它之前给它一个初始值。

qyuhtwio

qyuhtwio3#

您也可以使用以下代码:

DateTime? _startDate;
vlju58qv

vlju58qv4#

我确实有问题。有些对象不应该被直接初始化,因此创建延迟。例如,我不想在创建时初始化一个文件对象,但后来我使用了延迟,但flutter返回了一个错误。
所以跑:扑动跑--释放

相关问题