简体   繁体   English

我正在尝试创建将数字作为输入的 TextFormFields 列表,我想对所有这些数字求和

[英]I am trying to create list of TextFormFields which takes numbers as inputs and I want to Sum all those numbers

I am trying to create list of TextFormFields which takes numbers as inputs and I want to Sum all those numbers.我正在尝试创建将数字作为输入的 TextFormFields 列表,我想对所有这些数字求和。 When I click on a button on app bar new textformfield appears and user enters value..validator is also working fine...But I am not able to do the Sum.当我单击应用程序栏上的按钮时,会出现新的 textformfield 并且用户输入值..validator 也工作正常......但我无法进行求和。 When I used print in Onsaved method it displays all the entered values..If I use Controller, whatever the text we enter in formfield it is displaying same same in all the other textfields also..so controller is not working...I created TextFormField in different function and calling that function when button is pressed.当我在 Onsaved 方法中使用打印时,它会显示所有输入的值。如果我使用 Controller,无论我们在表单字段中输入什么文本,它在所有其他文本字段中也显示相同的内容。所以 controller 不起作用...我创建了TextFormField 在不同的 function 中,并在按下按钮时调用 function。 I created another button to go to next screen at the same time to validate which works fine... Below is the TextFormField code: Please help to Sum all the values entered in it:我同时创建了另一个按钮 go 到下一个屏幕以验证哪个工作正常......下面是 TextFormField 代码:请帮助对其中输入的所有值求和:

      child: TextFormField(
        // controller: _childController,
        decoration: InputDecoration(
            hintText: 'Value $_count',
            border: InputBorder.none,
            contentPadding: EdgeInsets.only(top: 5, left: 20)),
        keyboardType: TextInputType.number,
        style: TextStyle(
          color: Color.fromARGB(255, 0, 0, 0),
          fontWeight: FontWeight.w400,
          fontSize: 24,
        ),
        validator: (String value) {
          double sal = double.tryParse(value);
          if (sal == null) {
            return 'enter or delete row';
          }
        },
        onSaved: (String value) {
          // print(_childController.text);
          // print(value);              
          _mVal = value;
          double _mVal2 = double.tryParse(_mVal);              
          double _mVal3;
          
          print(_mVal);
          int k = 0;
          _children.forEach((element) {
           
            
            int y = int.tryParse(_mVal);
            k=k+y;
            print(k);
          }
          

Here is a quick example of how you can achieve this:以下是如何实现此目的的快速示例:

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Test(),
    ),
  );
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  final _formKey = GlobalKey<FormState>();
  List<TextEditingController> textFieldControllers = [];
  int numberOfTextFields = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          addNewTextField();
        },
      ),
      body: Stack(
        children: [
          Form(
            key: _formKey,
            child: ListView.builder(
              itemCount: numberOfTextFields,
              itemBuilder: (BuildContext context, int index) {
                return TextFormField(
                  validator: (String value) {
                    double sal = double.tryParse(value);
                    if (sal == null) {
                      return 'enter or delete row';
                    }
                    return null;
                  },
                  controller: textFieldControllers[index],
                );
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: TextButton(
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  showDialog(
                      context: context,
                      builder: (BuildContext context) {
                        return Center(
                          child: Material(
                            child: Container(
                              padding: EdgeInsets.all(10.0),
                              child: Text(
                                  'The sum is ${textFieldControllers.fold(0, (previousValue, element) => previousValue + int.parse(element.value.text))}'),
                            ),
                          ),
                        );
                      });
                }
              },
              child: Container(
                padding: EdgeInsets.all(10.0),
                color: Colors.redAccent,
                child: Text('Tap to sum'),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void addNewTextField() {
    textFieldControllers.add(TextEditingController());
    numberOfTextFields++;
    setState(() {});
  }

  @override
  void dispose() {
    textFieldControllers.forEach((textFieldController) => textFieldController.dispose());
    super.dispose();
  }
}

You can expand on this idea to remove textField if needed.如果需要,您可以扩展此想法以删除 textField。 Just don't forget to dispose your textFields.只是不要忘记处理您的文本字段。

How does this work : Each time a TextField Widget is create, an associated TextEditingController is created and given to the TextField.这是如何工作的:每次创建 TextField Widget 时,都会创建一个关联的 TextEditingController 并将其提供给 TextField。 When we want to sum, we just iterate on the TextEditingController list.当我们想要求和时,我们只需迭代 TextEditingController 列表即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想要列表中的数字总和并将其显示在文本小部件中 - i want sum of numbers from a list and display it in a Text widget 如何只接受 TextFormFields 中的数字? - How to accept only numbers in TextFormFields? 使用普通 List 或 ListView.Builder 时出现范围错误。 如何获得以下 TextFormFields 的总和? - Getting Range Error when I use normal List or ListView.Builder. How do I get the sum of below TextFormFields? 无论我做什么,表单中 TextFormFields 的下划线都不统一。 如何保持 TextFormFields 的所有下划线的粗细一致? - Underlines of TextFormFields in form not uniform no matter what I do. How to keep a uniform thickness for all underlines of TextFormFields? 我想在 flutter 中创建一个可重复使用的自定义 DropdownButton,这里提示名称和列表对于所有 DropdownButton 都是不同的 - I want to create a custom DropdownButton in flutter which can be reusable, here the hint name and list will be different for all DropdownButton 为什么我在尝试创建列表时收到 _TypeError? - Why am I getting a _TypeError when trying to create a list? 我想得到列表的总和数组 - I want to get sum array of list 如何在 Flutter 中将英文数字转换为另一种语言数字(我使用的是孟加拉语)? - How can I convert english numbers into another language numbers (I am using Bengali language) in Flutter? 我正在尝试使用从API获得的数据创建列表视图 - I am trying to create a list view with the data that I got from API 我是 flutter 的新手,我正在尝试创建此布局 - I am new to flutter and i am trying to create this layout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM