Search code examples
flutterflutter-widget

How to pass data in a stateful widget with constructor?


I am new to flutter and I think I miss a little piece of information about constructor and stateful widget. I tried many ways but always have an error. I just want to pass data into my stateful widget to manipulate from there.

Here is my Error

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

Here is my code

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;


Solution

  • You can just move it into 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;
        }
    }