Flutter 的 GlobalKeys 列表

Flutter List of GlobalKeys

我有一个动态列表,它由我在另一个屏幕上 select 的项目组成,在每个项目中我生成一个带有项目名称的标签,旁边是 TextField向该项目添加更多信息

控制器:

 controller: TextEditingController.fromValue(
  TextEditingValue(
   selection: new TextSelection.collapsed(
     offset: items[index].length),
    ),
  ),

标签:

Text(items[index].trim())

在可以是 1 个文本字段或 1000 个文本字段的文本字段中,当我单击保存按钮时,我需要获取写入其中的值并将其保存在列表中。为此,我创建了一个带有 globalkey 的表单,所以在进行验证后它会保存,但我只有 1 个 globakey,我可以有几个项目

final _formKey = GlobalKey<FormState>();

这是我的表格:

    Form(
    key: _formKey,
    child: Expanded(
      child: TextFormField(
         validator: (value) {
            if (int.parse(value) > 999999) {
              return 'error';
             }
            },
          decoration: InputDecoration(
          labelText: unitOfMeasurement,
            labelStyle: TextStyle(
            fontSize: 10,
            fontFamily: 'Montserrat',
            fontWeight: FontWeight.bold,
            color: Colors.grey),
           ),
           keyboardType: TextInputType.number,
           inputFormatters: [
             TextInputMask(
               mask: '\ !9+.99',
               placeholder: '0',
               maxPlaceHolders: 3,
               reverse: true)
             ],
           controller: TextEditingController.fromValue(
           TextEditingValue(
           selection: new TextSelection.collapsed(
           offset: items[index].length),
           ),
         ),
         onSaved: (String val){
         weigthItems.add(val.trim());
         print(val);
       },
      ),
    ),
  ),

    

还有我的钥匙:

final _formKey = GlobalKey<FormState>();

保存:

if(_formKey.currentState.validate()){
                      _formKey.currentState.save();
                      _receipt.weigthIngredients = weigthItems.toString().trim();
                    }

所有表单域只有一个 _formKey 就足够确保 Form() 是所有 TextFormField

的父级

示例:

Container(child: Form(
        key: _key,
        child: Column(
          children: [
            TextFormField(),
            TextFormField(),
            TextFormField(),
            TextFormField(),
            ..... // N number of form fields with validation
            TextButton(onPressed: (){
              if (_form.currentState.validate()){
                // validates all the field
              }
              
            }, child: Text('validate')),

          ],
        ),
      )

编辑:

您正在使用相同的密钥创建多个表单 我已经修改了你的代码,这应该可以工作


showFormDialogWeigth(BuildContext context) async {
  weigthItems.clear();
  items = isChecked.toList();

  return showDialog(
    context: context,
    builder: (context) {
      return StatefulBuilder(
        builder: (context, setState) {
          return AlertDialog(
            title: Text(
              'INFORME O PESO',
              style: TextStyle(
                  fontSize: 18,
                  fontFamily: 'Montserrat',
                  fontWeight: FontWeight.bold,
                  color: Colors.grey),
            ),
            content: Form(
              key: _formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    height: 250,
                    width: 280,
                    child: ListView.builder(
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return ListTile(
                          title: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  items[index].trim(),
                                  style: TextStyle(
                                      fontSize: 14,
                                      fontFamily: 'Montserrat',
                                      fontWeight: FontWeight.bold,
                                      color: Colors.grey),
                                ),
                              ),
                              Expanded(
                                child: TextFormField(
                                  validator: (value) {
                                    if (int.parse(value) > 999999) {
                                      return 'valor incorreto';
                                    }
                                    return null;
                                  },
                                  decoration: InputDecoration(
                                    labelText: unitOfMeasurement,
                                    labelStyle: TextStyle(
                                        fontSize: 10,
                                        fontFamily: 'Montserrat',
                                        fontWeight: FontWeight.bold,
                                        color: Colors.grey),
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [
                                    TextInputMask(
                                        mask: '\ !9+.99',
                                        placeholder: '0',
                                        maxPlaceHolders: 3,
                                        reverse: true)
                                  ],
                                  controller: TextEditingController.fromValue(
                                    TextEditingValue(
                                      selection: new TextSelection.collapsed(
                                          offset: items[index].length),
                                    ),
                                  ),
                                  onSaved: (String val){
                                    weigthItems.add(val.trim());
                                    print(val);
                                  },
                                  // onChanged: (value) async {
                                  //   _debouncer.run(() {
                                  //     weigthItems.add(value.trim());
                                  //     print(weigthItems);
                                  //   });
                                  // },
                                ),
                              ),
                            ],
                          ),
                          subtitle: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  timeOrTurns.toString(),
                                  style: TextStyle(
                                      fontSize: 10,
                                      fontFamily: 'Montserrat',
                                      fontWeight: FontWeight.bold,
                                      color: Colors.grey),
                                ),
                              ),
                              Expanded(
                                child: TextFormField(
                                  decoration: InputDecoration(
                                    hintText: "Max 600",
                                    hintStyle: TextStyle(
                                        fontSize: 10,
                                        fontFamily: 'Montserrat',
                                        fontWeight: FontWeight.bold,
                                        color: Colors.grey),
                                  ),
                                  keyboardType: TextInputType.number,
                                  controller: TextEditingController.fromValue(
                                    TextEditingValue(
                                      selection: new TextSelection.collapsed(
                                          offset: items[index].length),
                                    ),
                                  ),
                                  onChanged: (value) async {
                                    if (int.parse(value) < 600) {
                                      _debouncer.run(
                                            () {
                                          timeItems.add(value);
                                          print(timeItems);
                                        },
                                      );
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                      itemCount: items.length,
                    ),
                  ),
                  Container(
                    width: 200,
                    height: 30,
                    child: TextField(
                      maxLength: 2,
                      keyboardType: TextInputType.number,
                      controller: totalTime,
                      decoration: InputDecoration(
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey,
                            ),
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          hintText: "TEMPO TOTAL DE MISTURA",
                          hintStyle: TextStyle(
                              fontSize: 10,
                              fontFamily: 'Montserrat',
                              fontWeight: FontWeight.bold,
                              color: Colors.grey)),
                    ),
                  ),
                ],
              ),
            ),
            actions: <Widget>[
              FlatButton(
                onPressed: () async {
                  Navigator.pop(context);
                },
                child: Text(
                  'VOLTAR',
                  style: TextStyle(color: Colors.green),
                ),
              ),
              FlatButton(
                onPressed: () async {

                  if(_formKey.currentState.validate()){
                    _formKey.currentState.save();
                    _receipt.weigthIngredients = weigthItems.toString().trim();
                  }

                  _receipt.unitOfMeasurement = unitOfMeasurement.toString();
                  _receipt.timeOrTurns = timeOrTurns.toString();
                  _receipt.valueMix = timeItems.toString();
                  _receipt.totalMix = totalTime.text;

                  var result = await _receiptService.saveReceipt(_receipt);
                  if (result > 0) {
                    getAllReceipt();
                    print(timeItems);
                    print(weigthItems);
                    print(totalTime);
                    Navigator.pushNamed(context, AppRoutes.RECEIPTS);
                  }
                },
                child: Text(
                  'SALVAR',
                  style: TextStyle(color: Colors.green),
                ),
              ),
            ],
          );
        },
      );
    },
  );
}

showFormDialogWeigth(BuildContext context) async {
    weigthItems.clear();
    items = isChecked.toList();

    return showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: Text(
                'INFORME O PESO',
                style: TextStyle(
                    fontSize: 18,
                    fontFamily: 'Montserrat',
                    fontWeight: FontWeight.bold,
                    color: Colors.grey),
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Container(
                    height: 250,
                    width: 280,
                    child: ListView.builder(
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return ListTile(
                          title: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  items[index].trim(),
                                  style: TextStyle(
                                      fontSize: 14,
                                      fontFamily: 'Montserrat',
                                      fontWeight: FontWeight.bold,
                                      color: Colors.grey),
                                ),
                              ),
                              Form(
                                key: _formKey,
                                child: Expanded(
                                  child: TextFormField(
                                    validator: (value) {
                                      if (int.parse(value) > 999999) {
                                        return 'valor incorreto';
                                      }
                                    },
                                    decoration: InputDecoration(
                                      labelText: unitOfMeasurement,
                                      labelStyle: TextStyle(
                                          fontSize: 10,
                                          fontFamily: 'Montserrat',
                                          fontWeight: FontWeight.bold,
                                          color: Colors.grey),
                                    ),
                                    keyboardType: TextInputType.number,
                                    inputFormatters: [
                                      TextInputMask(
                                          mask: '\ !9+.99',
                                          placeholder: '0',
                                          maxPlaceHolders: 3,
                                          reverse: true)
                                    ],
                                    controller: TextEditingController.fromValue(
                                      TextEditingValue(
                                        selection: new TextSelection.collapsed(
                                            offset: items[index].length),
                                      ),
                                    ),
                                    onSaved: (String val){
                                      weigthItems.add(val.trim());
                                      print(val);
                                    },
                                    // onChanged: (value) async {
                                    //   _debouncer.run(() {
                                    //     weigthItems.add(value.trim());
                                    //     print(weigthItems);
                                    //   });
                                    // },
                                  ),
                                ),
                              ),
                            ],
                          ),
                          subtitle: Row(
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  timeOrTurns.toString(),
                                  style: TextStyle(
                                      fontSize: 10,
                                      fontFamily: 'Montserrat',
                                      fontWeight: FontWeight.bold,
                                      color: Colors.grey),
                                ),
                              ),
                              Expanded(
                                child: TextFormField(
                                  decoration: InputDecoration(
                                    hintText: "Max 600",
                                    hintStyle: TextStyle(
                                        fontSize: 10,
                                        fontFamily: 'Montserrat',
                                        fontWeight: FontWeight.bold,
                                        color: Colors.grey),
                                  ),
                                  keyboardType: TextInputType.number,
                                  controller: TextEditingController.fromValue(
                                    TextEditingValue(
                                      selection: new TextSelection.collapsed(
                                          offset: items[index].length),
                                    ),
                                  ),
                                  onChanged: (value) async {
                                    if (int.parse(value) < 600) {
                                      _debouncer.run(
                                        () {
                                          timeItems.add(value);
                                          print(timeItems);
                                        },
                                      );
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                      itemCount: items.length,
                    ),
                  ),
                  Container(
                    width: 200,
                    height: 30,
                    child: TextField(
                      maxLength: 2,
                      keyboardType: TextInputType.number,
                      controller: totalTime,
                      decoration: InputDecoration(
                          disabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: Colors.grey,
                            ),
                            borderRadius: BorderRadius.circular(10.0),
                          ),
                          hintText: "TEMPO TOTAL DE MISTURA",
                          hintStyle: TextStyle(
                              fontSize: 10,
                              fontFamily: 'Montserrat',
                              fontWeight: FontWeight.bold,
                              color: Colors.grey)),
                    ),
                  ),
                ],
              ),
              actions: <Widget>[
                FlatButton(
                  onPressed: () async {
                    Navigator.pop(context);
                  },
                  child: Text(
                    'VOLTAR',
                    style: TextStyle(color: Colors.green),
                  ),
                ),
                FlatButton(
                  onPressed: () async {

                    if(_formKey.currentState.validate()){
                      _formKey.currentState.save();
                      _receipt.weigthIngredients = weigthItems.toString().trim();
                    }

                    _receipt.unitOfMeasurement = unitOfMeasurement.toString();
                    _receipt.timeOrTurns = timeOrTurns.toString();
                    _receipt.valueMix = timeItems.toString();
                    _receipt.totalMix = totalTime.text;

                    var result = await _receiptService.saveReceipt(_receipt);
                    if (result > 0) {
                      getAllReceipt();
                      print(timeItems);
                      print(weigthItems);
                      print(totalTime);
                      Navigator.pushNamed(context, AppRoutes.RECEIPTS);
                    }
                  },
                  child: Text(
                    'SALVAR',
                    style: TextStyle(color: Colors.green),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }