Флаттер: Stepper onStep Продолжение не стреляет

Можете ли вы сказать мне, что не так в моем коде?

Widget _createProfileStepper() {
int currentStep = 0;

List<Step> createAccSteps = [
  new Step(
    title: Container(),
    content: new Text('This is the first step.'),
    isActive: currentStep >= 0,
    state: currentStep >= 0 ? StepState.editing : StepState.disabled,
  ),
  new Step(
    title: Container(),
    content: new Text('This is the second step.'),
    isActive: currentStep >= 0,
    state: currentStep >= 1 ? StepState.editing : StepState.disabled,
  ),
  new Step(
    title: Container(),
    content: new Text('This is the third step.'),
    isActive: currentStep >= 0,
    state: currentStep >= 2 ? StepState.editing : StepState.disabled,
  ),
  new Step(
    title: Container(),
    content: new Text('This is the second step.'),
    isActive: currentStep >= 0,
    state: currentStep >= 3 ? StepState.editing : StepState.disabled,
  ),
  new Step(
    title: Container(),
    content: new Text('This is the third step.'),
    isActive: currentStep >= 0,
    state: currentStep >= 4 ? StepState.editing : StepState.disabled,
  ),
];

return Scaffold(
  appBar: AppBar(
    title: Text("Create Profile"),
  ),
  body: Stepper(
    type: StepperType.horizontal,
    currentStep: currentStep,
    onStepTapped: (step) {
      setState(() {
        currentStep = step;
      });
    },
    onStepContinue: () {
      setState(() {
        if (currentStep < createAccSteps.length - 1) {
          currentStep = currentStep + 1;
        } else {}
      });
    },
    onStepCancel: () {
      setState(() {
        if(currentStep > 0){
          currentStep = currentStep - 1;
        }
        else {
          currentStep = 0;
        }
      });
    },
    steps: createAccSteps,
  ),
);
}

Я следовал всем примерам степпера Флаттера, но все равно не повезло. Я могу нажать кнопку "Продолжить", но она не переходит к другому шагу. Я что-то забыл? Я создал класс Stateful Widget, после чего кнопка вызывала бы меня _createProfileStepper(). Благодарю.

2 ответа

Решение

Имея весь код в _createProfileStepper() виджет становится без сохранения состояния, даже если он используется в виджете с состоянием. Это потому, что всякий раз, когда build метод виджета с состоянием перезапускается, он будет вызывать _createProfileStepper() что приведет к повторной инициализации всего виджета Stepper, т. е. воссозданию Stepper, и, таким образом, continue не работает.

Почему бы не создать виджет с сохранением состояния для одного шага и использовать этот виджет вместо того, из которого вы получаете _createProfileStepper(), Например:

class _SimpleWidgetState extends State<SimpleWidget> {
  int currentStep = 0;

  List<Step> steps = [
    Step(
        title: Text("Step One"),
        content: Text("This is the first step"),
        isActive: true
    ),
    Step(
      title: Text("Step Two"),
      content: Text("This is the second step"),
      isActive: true,
    ),
    Step(
      title: Text("Step Three"),
      content: Text("This is the third step"),
      isActive: true,
    ),
    Step(
      title: Text("Step Four"),
      content: Text("This is the fourth step"),
      isActive: false,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stepper(
        steps: steps,
        currentStep: currentStep,
        type: StepperType.vertical,
        onStepTapped: (step) {
          setState(() {
            currentStep = step;
            print(step);
          });
        },
        onStepCancel: () {
          setState(() {
            currentStep > 0 ? currentStep -= 1 : currentStep = 0;
          });
        },
        onStepContinue: () {
          setState(() {
            currentStep < steps.length - 1 ? currentStep += 1 : currentStep = 0;
          });
        },
      ),
    );
  }
}

class SimpleWidget extends StatefulWidget {
  @override
  _SimpleWidgetState createState() {
    // TODO: implement createState
    return _SimpleWidgetState();
  }
}

Тогда используйте SimpleWidget() где бы вы _createProfileStepper()

Во-вторых, что касается вашего вопроса о вашем доступе к списку currentStep, потому что только static члены могут быть использованы для инициализации

Поэтому вы не можете получить доступ к своему текущему шагу из внутреннего списка для начала.

"isActive" также должен быть логическим (и влияет только на стилизацию https://docs.flutter.io/flutter/material/Step/isActive.html)

Также немного странно иметь пустой Container() в качестве заголовка, вы можете либо удалить его, либо добавить туда номер шага.

Попробуйте изменить ваши шаги на

Step(
    title: Text("Step One"),
    content: new Text("This is the first step."),
    isActive: true
),
Другие вопросы по тегам