Flutter - 在同一函数中添加 'await' 时 VoidCallback 调用 null

Flutter - VoidCallback called on null when adding 'await' in the same function

我有一个 VoidCallback 从小部件传递到另一个小部件,当从第二个小部件调用时它正常运行,如果我将 'await' 添加到同一函数中的另一个语句它会中断并显示 "called on null" 错误

第一个小部件:

  refreshLocalList() async {
    Logger.log("Refrishing list");
    setState(() {appointmentsList=AppointmentsController.getLocalList();});
  }
.
.
.
onTap: (){
    Navigator.of(context).push(MaterialPageRoute(
    builder: (context) => NewAppointment(time:times9to2[index],date: date,cameraId: cameraId.toString(),refreshLocalList: refreshLocalList,showInSnackBar: showInSnackBar,)));
                        },

第二个小部件:

    class NewAppointment extends StatefulWidget {
      final String time;
      final String date;
      final String cameraId;
      final VoidCallback refreshLocalList;
      final void Function(String msg) showInSnackBar;
      const NewAppointment({Key key, this.time, this.date,this.cameraId,this.refreshLocalList,this.showInSnackBar}) : super(key: key);
      @override
      _NewAppointmentState createState() => _NewAppointmentState();
    }
class _NewAppointmentState extends State<NewAppointment> {
  Doctor doctor = Doctor();
  _NewAppointmentState();
  Widget build(BuildContext context) {
    return MaterialApp(
.
.
.
child: Text("Submit",
                                ),
                                onPressed: () async {

                                  widget.refreshLocalList();
                                  Appointment newAppointmet = Appointment(doctor_id: DoctorsController.getDoctorIdByName(doctorNameController.text),
                                      date: widget.date,time: widget.time,description: descriptionFieldController.text,camera_id: widget.cameraId);
                                  AppointmentsController.addToLocalList(newAppointmet);
                                  await Queries.createAppointment(doctorNameController.text,widget.date,widget.time,descriptionFieldController.text,widget.cameraId);
                                  Navigator.of(context).pop();
                                  widget.showInSnackBar("Appointment created");
                                }),

回调是refreshLocalList()

另一个回调 widget.showInSnackBar(String) 在这两种情况下都工作正常。

如果我在 Queries.createAppointment 之前删除 "await",一切正常。

错误:

> I/flutter (14062): full doctors map size 57 E/flutter (14062):
> [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception:
> NoSuchMethodError: The method 'call' was called on null. E/flutter
> (14062): Receiver: null E/flutter (14062): Tried calling: call()

这是一个理论:可能它在没有 await 的情况下也能工作,因为 NewAppointment 有机会弹出并且您的第一个小部件变得可见,所以那里的 setState() 工作得很好。

但是,当您 await 时,它不会弹出并且当 setState() 发生时第一个小部件不可见。

尝试将 Navigator.of(context).pop(); 行移到等待行之前