如何使用构造函数在有状态小部件中传递数据?

How to pass data in a stateful widget with constructor?

我是 Flutter 的新手,我想我错过了一些关于构造函数和有状态小部件的信息。我尝试了很多方法,但总是出错。我只想将数据传递到我的有状态小部件以从那里进行操作。

这是我的错误

The instance member 'widget' can't be accessed in an initializer.
Try replacing the reference to the instance member with a different expression

这是我的代码

class CreateEducatorEventForm extends StatefulWidget {
  final DateTime day = DateTime.now();
  final String favoriteId = '';

  CreateEducatorEventForm(DateTime day, String favoriteId);

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

class _CreateEducatorEventFormState extends State<CreateEducatorEventForm> {
  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;
  String _eventName = '';
  String _eventDescription = '';
  DateTime _eventDateStart = widget.day;
  DateTime _eventDateFinish = widget.day;

您可以将其移动到 initState

class _CreateEducatorEventFormState extends State<CreateEducatorEventForm> {
    final _formKey = GlobalKey<FormState>();
    bool _isLoading = false;
    String _eventName = '';
    String _eventDescription = '';
    DateTime _eventDateStart;
    DateTime _eventDateFinish;

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

        _eventDateStart = widget.day;
        _eventDateFinish = widget.day;
    }
}

公平地说,除非你真的需要将它存储到你的状态中(比如,如果它真的参与了你的小部件的生命周期),你应该在需要时通过 widget.day 引用它.