Флаттер: Stepper onStep Продолжение не стреляет - PullRequest
0 голосов
/ 16 октября 2018

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

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 ]

0 голосов
/ 17 октября 2018

При наличии всего кода в _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 члены могут быть использованы для инициализации

0 голосов
/ 16 октября 2018

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

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

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

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

Step(
    title: Text("Step One"),
    content: new Text("This is the first step."),
    isActive: true
),
...