So I'm actually pretty new with flutter and this is my first project. Everything went well, until this problem came up. Recently, I added a stepperBody into my page and in one of the steps there should be a datePicker integrated. Unfortunately, I can't really resolve the problem that is coming up. I'm constantly getting an "Only static members can be accessed in initializers." error. Help is appreciated.

I'm using the flutter_datetime_picker plugin.

Here's my code:

class StepperBody extends StatefulWidget {
  @override
  _StepperBodyState createState() =>  _StepperBodyState();
}

class _StepperBodyState extends State<StepperBody> {
  String _date = "Not set";
  int currStep = 0;
  static var _focusNode =  FocusNode();
  GlobalKey<FormState> _formKey =  GlobalKey<FormState>();
  static MyData data =  MyData();

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
      print('Has focus: $_focusNode.hasFocus');
    });
  }

  List<Step> steps = [
    Step(
        title: const Text('Name',
          style: TextStyle(
            fontFamily: 'Maax',
            fontSize: 20,
          ),),
        //subtitle: const Text('Enter your name'),
        isActive: true,
        //state: StepState.error,
        state: StepState.indexed,
        content: Form(
          key: formKeys[0],
          child: Column(
            children: <Widget>[
              TextFormField(
                style: TextStyle(
                  fontFamily: 'Maax',
                  fontWeight: FontWeight.w500,
                ),
                focusNode: _focusNode,
                keyboardType: TextInputType.text,
                autocorrect: false,
                onSaved: (String value) {
                  data.title = value;
                },
                maxLines: 1,
                //initialValue: 'Aseem Wangoo',
                validator: (value) {
                  if (value.isEmpty || value.length < 1) {
                    return 'Please enter title';
                  }
                },
                decoration:  InputDecoration(
                    labelText: 'What is the name of the test?',
                    hintText: 'Enter a name',
                    //filled: true,
                    icon: const FaIcon(FontAwesomeIcons.signature),
                    labelStyle:
                    TextStyle(decorationStyle: TextDecorationStyle.solid, fontFamily: 'Maax', fontWeight: FontWeight.w500)),
              ),
            ],
          ),
        )),
    Step(
        title: const Text('Date'),
        //subtitle: const Text('Subtitle'),
        isActive: true,
        //state: StepState.editing,
        state: StepState.indexed,
        content: Form(
          key: formKeys[1],
          child: Column(
            children: <Widget>[
              RaisedButton(
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5.0)),
                elevation: 4.0,
                onPressed: () {
                  DatePicker.showDatePicker(context,
                      theme: DatePickerTheme(
                        containerHeight: 210.0,
                      ),
                      showTitleActions: true,
                      minTime: DateTime(2000, 1, 1),
                      maxTime: DateTime(2022, 12, 31), onConfirm: (date) {
                        print('confirm $date');
                        _date = '${date.year} - ${date.month} - ${date.day}';
                        setState(() {});
                      }, currentTime: DateTime.now(), locale: LocaleType.en);
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 50.0,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Container(
                            child: Row(
                              children: <Widget>[
                                Icon(
                                  Icons.date_range,
                                  size: 18.0,
                                  color: Colors.teal,
                                ),
                                Text(
                                  " $_date",
                                  style: TextStyle(
                                      color: Colors.teal,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                      Text(
                        "  Change",
                        style: TextStyle(
                            color: Colors.teal,
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0),
                      ),
                    ],
                  ),
                ),
                color: Colors.white,
              ),
              TextFormField(
                keyboardType: TextInputType.phone,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || value.length < 10) {
                    return 'Please enter valid number';
                  }
                },
                onSaved: (String value) {
                  data.days = value;
                },
                maxLines: 1,
                decoration:  InputDecoration(
                    labelText: 'Enter your number',
                    hintText: 'Enter a number',
                    icon: const Icon(Icons.phone),
                    labelStyle:
                    TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
    Step(
        title: const Text('Email'),
        // subtitle: const Text('Subtitle'),
        isActive: true,
        state: StepState.indexed,
        // state: StepState.disabled,
        content:  Form(
          key: formKeys[2],
          child: Column(
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.emailAddress,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || !value.contains('@')) {
                    return 'Please enter valid email';
                  }
                },
                onSaved: (String value) {
                  data.words = value;
                },
                maxLines: 1,
                decoration:  InputDecoration(
                    labelText: 'Enter your email',
                    hintText: 'Enter a email address',
                    icon: const Icon(Icons.email),
                    labelStyle:
                    TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
    Step(
        title: const Text('Age'),
        // subtitle: const Text('Subtitle'),
        isActive: true,
        state: StepState.indexed,
        content:  Form(
          key: formKeys[3],
          child: Column(
            children: <Widget>[
              TextFormField(
                keyboardType: TextInputType.number,
                autocorrect: false,
                validator: (value) {
                  if (value.isEmpty || value.length > 2) {
                    return 'Please enter valid age';
                  }
                },
                maxLines: 1,
                onSaved: (String value) {
                  data.rep = value;
                },
                decoration:  InputDecoration(
                    labelText: 'Enter your age',
                    hintText: 'Enter age',
                    icon: const Icon(Icons.explicit),
                    labelStyle:
                    TextStyle(decorationStyle: TextDecorationStyle.solid)),
              ),
            ],
          ),
        )),
    //  Step(
    //     title: const Text('Fifth Step'),
    //     subtitle: const Text('Subtitle'),
    //     isActive: true,
    //     state: StepState.complete,
    //     content: const Text('Enjoy Step Fifth'))
  ];

  @override
  Widget build(BuildContext context) {
    void showSnackBarMessage(String message,
        [MaterialColor color = Colors.red]) {
      Scaffold
          .of(context)
          .showSnackBar( SnackBar(content:  Text(message)));
    }

    void _submitDetails() {
      final FormState formState = _formKey.currentState;

      if (!formState.validate()) {
        showSnackBarMessage('Please enter correct data');
      } else {
        formState.save();
        print("Name: ${data.title}");
        print("Phone: ${data.days}");
        print("Email: ${data.words}");
        print("Age: ${data.rep}");

        showDialog(
            context: context,
            child:  AlertDialog(
              title:  Text("Details"),
              //content:  Text("Hello World"),
              content:  SingleChildScrollView(
                child:  ListBody(
                  children: <Widget>[
                    Text("Name : " + data.title),
                    Text("Phone : " + data.days),
                    Text("Email : " + data.words),
                    Text("Age : " + data.rep),
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  child:  Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ));
      }
    }

    return  Container(
        child:  Form(
          key: _formKey,
          child:  ListView(children: <Widget>[
            Stepper(
              steps: steps,
              type: StepperType.vertical,
              currentStep: this.currStep,
              onStepContinue: () {
                setState(() {
                  if(formKeys[currStep].currentState.validate()) {
                    if (currStep < steps.length - 1) {
                      currStep = currStep + 1;
                    } else {
                      currStep = 0;
                    }
                  }
                  // else {
                  // Scaffold
                  //     .of(context)
                  //     .showSnackBar( SnackBar(content:  Text('$currStep')));

                  // if (currStep == 1) {
                  //   print('First Step');
                  //   print('object' + FocusScope.of(context).toStringDeep());
                  // }

                  // }
                });
              },
              onStepCancel: () {
                setState(() {
                  if (currStep > 0) {
                    currStep = currStep - 1;
                  } else {
                    currStep = 0;
                  }
                });
              },
              onStepTapped: (step) {
                setState(() {
                  currStep = step;
                });
              },
            ),
            RaisedButton(
              child:  Text(
                'Save details',
                style:  TextStyle(color: Colors.white),
              ),
              onPressed: _submitDetails,
              color: Colors.blue,
            ),

          ]),
        ));
  }
}


Solution 1: chunhunghan

You can copy paste run full code below
You can move steps definition to build to avoid Only static members can be accessed in initializers and allow _date to change after setState
To avoid known issue of flutter_datetime_picker, I use this git

flutter_datetime_picker:
    git:
      url: https://github.com/derohimat/flutter_datetime_picker.git

code snippet

@override
  Widget build(BuildContext context) {
    steps = [
      Step(

working demo

enter image description here

full code

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

class MyData {
  String title;
  String days;
  String words;
  String rep;

  MyData({this.title, this.days, this.words, this.rep});
}

class StepperBody extends StatefulWidget {
  @override
  _StepperBodyState createState() => _StepperBodyState();
}

class _StepperBodyState extends State<StepperBody> {
  String _date = "Not set";
  int currStep = 0;
  static var _focusNode = FocusNode();
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  static MyData data = MyData();

  List<GlobalKey<FormState>> formKeys = [
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>(),
    GlobalKey<FormState>()
  ];
  List<Step> steps = [];

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      setState(() {});
      print('Has focus: $_focusNode.hasFocus');
    });

  }

  @override
  Widget build(BuildContext context) {
    steps = [
      Step(
          title: const Text(
            'Name',
            style: TextStyle(
              fontFamily: 'Maax',
              fontSize: 20,
            ),
          ),
          //subtitle: const Text('Enter your name'),
          isActive: true,
          //state: StepState.error,
          state: StepState.indexed,
          content: Form(
            key: formKeys[0],
            child: Column(
              children: <Widget>[
                TextFormField(
                  style: TextStyle(
                    fontFamily: 'Maax',
                    fontWeight: FontWeight.w500,
                  ),
                  focusNode: _focusNode,
                  keyboardType: TextInputType.text,
                  autocorrect: false,
                  onSaved: (String value) {
                    data.title = value;
                  },
                  maxLines: 1,
                  //initialValue: 'Aseem Wangoo',
                  validator: (value) {
                    if (value.isEmpty || value.length < 1) {
                      return 'Please enter title';
                    }
                  },
                  decoration: InputDecoration(
                      labelText: 'What is the name of the test?',
                      hintText: 'Enter a name',
                      //filled: true,
                      icon: Icon(Icons.add),
                      labelStyle: TextStyle(
                          decorationStyle: TextDecorationStyle.solid,
                          fontFamily: 'Maax',
                          fontWeight: FontWeight.w500)),
                ),
              ],
            ),
          )),
      Step(
          title: const Text('Date'),
          //subtitle: const Text('Subtitle'),
          isActive: true,
          //state: StepState.editing,
          state: StepState.indexed,
          content: Form(
            key: formKeys[1],
            child: Column(
              children: <Widget>[
                RaisedButton(
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5.0)),
                  elevation: 4.0,
                  onPressed: () {
                    DatePicker.showDatePicker(context,
                        theme: DatePickerTheme(
                          containerHeight: 210.0,
                        ),
                        showTitleActions: true,
                        minTime: DateTime(2000, 1, 1),
                        maxTime: DateTime(2022, 12, 31), onConfirm: (date) {
                          print('confirm $date');
                          _date = '${date.year} - ${date.month} - ${date.day}';
                          print('date ${_date}');
                          setState(() {});
                        }, currentTime: DateTime.now(), locale: LocaleType.en);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    height: 50.0,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              child: Row(
                                children: <Widget>[
                                  Icon(
                                    Icons.date_range,
                                    size: 18.0,
                                    color: Colors.teal,
                                  ),
                                  Text(
                                    " $_date",
                                    style: TextStyle(
                                        color: Colors.teal,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 18.0),
                                  ),
                                ],
                              ),
                            )
                          ],
                        ),
                        Text(
                          "  Change",
                          style: TextStyle(
                              color: Colors.teal,
                              fontWeight: FontWeight.bold,
                              fontSize: 18.0),
                        ),
                      ],
                    ),
                  ),
                  color: Colors.white,
                ),
                TextFormField(
                  keyboardType: TextInputType.phone,
                  autocorrect: false,
                  validator: (value) {
                    if (value.isEmpty || value.length < 10) {
                      return 'Please enter valid number';
                    }
                  },
                  onSaved: (String value) {
                    data.days = value;
                  },
                  maxLines: 1,
                  decoration: InputDecoration(
                      labelText: 'Enter your number',
                      hintText: 'Enter a number',
                      icon: const Icon(Icons.phone),
                      labelStyle: TextStyle(
                          decorationStyle: TextDecorationStyle.solid)),
                ),
              ],
            ),
          )),
      Step(
          title: const Text('Email'),
          // subtitle: const Text('Subtitle'),
          isActive: true,
          state: StepState.indexed,
          // state: StepState.disabled,
          content: Form(
            key: formKeys[2],
            child: Column(
              children: <Widget>[
                TextFormField(
                  keyboardType: TextInputType.emailAddress,
                  autocorrect: false,
                  validator: (value) {
                    if (value.isEmpty || !value.contains('@')) {
                      return 'Please enter valid email';
                    }
                  },
                  onSaved: (String value) {
                    data.words = value;
                  },
                  maxLines: 1,
                  decoration: InputDecoration(
                      labelText: 'Enter your email',
                      hintText: 'Enter a email address',
                      icon: const Icon(Icons.email),
                      labelStyle: TextStyle(
                          decorationStyle: TextDecorationStyle.solid)),
                ),
              ],
            ),
          )),
      Step(
          title: const Text('Age'),
          // subtitle: const Text('Subtitle'),
          isActive: true,
          state: StepState.indexed,
          content: Form(
            key: formKeys[3],
            child: Column(
              children: <Widget>[
                TextFormField(
                  keyboardType: TextInputType.number,
                  autocorrect: false,
                  validator: (value) {
                    if (value.isEmpty || value.length > 2) {
                      return 'Please enter valid age';
                    }
                  },
                  maxLines: 1,
                  onSaved: (String value) {
                    data.rep = value;
                  },
                  decoration: InputDecoration(
                      labelText: 'Enter your age',
                      hintText: 'Enter age',
                      icon: const Icon(Icons.explicit),
                      labelStyle: TextStyle(
                          decorationStyle: TextDecorationStyle.solid)),
                ),
              ],
            ),
          )),
      //  Step(
      //     title: const Text('Fifth Step'),
      //     subtitle: const Text('Subtitle'),
      //     isActive: true,
      //     state: StepState.complete,
      //     content: const Text('Enjoy Step Fifth'))
    ];

    void showSnackBarMessage(String message,
        [MaterialColor color = Colors.red]) {
      Scaffold.of(context).showSnackBar(SnackBar(content: Text(message)));
    }

    void _submitDetails() {
      final FormState formState = _formKey.currentState;

      if (!formState.validate()) {
        showSnackBarMessage('Please enter correct data');
      } else {
        formState.save();
        print("Name: ${data.title}");
        print("Phone: ${data.days}");
        print("Email: ${data.words}");
        print("Age: ${data.rep}");

        showDialog(
            context: context,
            child: AlertDialog(
              title: Text("Details"),
              //content:  Text("Hello World"),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text("Name : " + data.title),
                    Text("Phone : " + data.days),
                    Text("Email : " + data.words),
                    Text("Age : " + data.rep),
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ));
      }
    }

    return Container(
        child: Form(
      key: _formKey,
      child: ListView(children: <Widget>[
        Stepper(
          steps: steps,
          type: StepperType.vertical,
          currentStep: this.currStep,
          onStepContinue: () {
            setState(() {
              if (formKeys[currStep].currentState.validate()) {
                if (currStep < steps.length - 1) {
                  currStep = currStep + 1;
                } else {
                  currStep = 0;
                }
              }
              // else {
              // Scaffold
              //     .of(context)
              //     .showSnackBar( SnackBar(content:  Text('$currStep')));

              // if (currStep == 1) {
              //   print('First Step');
              //   print('object' + FocusScope.of(context).toStringDeep());
              // }

              // }
            });
          },
          onStepCancel: () {
            setState(() {
              if (currStep > 0) {
                currStep = currStep - 1;
              } else {
                currStep = 0;
              }
            });
          },
          onStepTapped: (step) {
            setState(() {
              currStep = step;
            });
          },
        ),
        RaisedButton(
          child: Text(
            'Save details',
            style: TextStyle(color: Colors.white),
          ),
          onPressed: _submitDetails,
          color: Colors.blue,
        ),
      ]),
    ));
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: "test",),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(child: StepperBody()),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}