Флаттер: как использовать ключ формы в нескольких классах - PullRequest
0 голосов
/ 22 апреля 2020

Я создаю экран с формой для пользователей, чтобы создать рецепт (это класс AddRecipeForm). Я создал новый класс (AddRecipeSteps) для добавления полей текстовой формы, где пользователь определяет шаги рецепта. Как я могу получить доступ / передать ключ формы в классе AddRecipeForm, в другой класс AddRecipeSteps? Чтобы иметь возможность сохранить состояние и использовать валидатор. У меня также есть класс Recipe, где входные данные «хранятся» как объект Recipe. Для полного кода: https://codeshare.io/5QRb17, https://codeshare.io/5ZOzV7, https://codeshare.io/2BRBrp

Это часть класса AddRecipeForm:

class AddRecipeForm extends StatefulWidget {
  @override
  _AddRecipeFormState createState() => _AddRecipeFormState();
}

class _AddRecipeFormState extends State<AddRecipeForm> {
  final formKey = GlobalKey<FormState>();
  Recipe recipe = Recipe();

  int step = 1;

  @override
  Widget build(BuildContext context) {

    return Form(
      key: formKey,
      child: ListView(
        children: <Widget>[
          //...
          AddRecipeSteps(
            //TODO: want to pass the formkey to AddRecipeSteps class
          ),
          //...
        ],
      ),
    );
  }

Это класс AddRecipeSteps:

import 'package:cibus/services/recipe.dart';
import 'package:flutter/material.dart';
import 'my_text_form_field.dart';

class AddRecipeSteps extends StatefulWidget {
  @override
  _AddRecipeStepsState createState() => _AddRecipeStepsState();
}

class _AddRecipeStepsState extends State<AddRecipeSteps> {
  int steps = 1;

  List<Widget> buildSteps() {
    List<Widget> listOfSteps = [];

    for (int i = 1; i <= steps; i++)
      listOfSteps.add(Padding(
        padding: const EdgeInsets.all(8.0),
        child: MyTextFormField(
          labelText: "Step $i",
          validator: (String step) {
            if (step.isEmpty) {
              return 'Enter a Description';
            }
            else {
              //we want to use formKey from AddRecipeForm class
              formKey.currentState.save();
              return null;
            }
          },
          onSaved: (String step){
            //want to add the input to the recipe object
            recipe.steps.add(step);
          },
        ),
      ));

    listOfSteps.add(
      Center(
        child: RaisedButton(
          child: Text("Add step"),
          onPressed: () {
            setState(() {
              steps++;
            });
          },
        ),
      ),
    );

    return listOfSteps;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
        children: buildSteps(),
    );
  }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...