【问题标题】:How to access dynamic input fields values on button click in flutter如何在颤动中单击按钮时访问动态输入字段值
【发布时间】:2022-11-05 23:23:07
【问题描述】:

我正在开发一个考勤应用程序,我将工资分配给工人。我想将所有给工人的工资存储到数据库中。但问题是我想在按钮点击时访问所有给定的值。我不知道它是如何在颤动中完成的。我是初学者。

我已经给出了所有代码和我想要的输出图像。

模拟器图片

这是我的代码...

考勤画面

...rest code...
 floatingActionButton: FloatingActionButton(
        onPressed: () {
          showDialog(
            context: context,
            barrierDismissible: false, // user must tap button!
            builder: (BuildContext context) {
              return AlertDialog(
                title: const Text('Upload Patti'),
                content: SingleChildScrollView(
                  child: ListBody(
                    children: [
                      TextFormField(
                        controller: _mainWagesController,
                        decoration: const InputDecoration(
                          border: OutlineInputBorder(),
                          hintText: "Enter Amount",
                          prefixIcon: Icon(Icons.wallet, color: Colors.blue),
                        ),
                      ),
                    ],
                  ),
                ),
                actions: <Widget>[
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                      newWages = _mainWagesController.text;
                      setState(() {});
                    },
                    child: const Text("Assign Wages"),
                  ),
                ],
              );
            },
          );
        },
        child: const Icon(Icons.check_circle),
      ),
body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.00),
          child: Column(children: [
            const SizedBox(
              height: 20,
            ),
            Center(
              child: Text(
                "Date :  ${DateFormat.yMMMEd().format(DateTime.parse(widget.attendanceDate.toString()))}",
                style: const TextStyle(fontSize: 20),
              ),
            ),
            const SizedBox(
              height: 20,
            ),
            FutureBuilder(
              future: SupervisorAttendanceServices.getAttendancesDetailsList(
                  widget.attendanceId),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.hasData) {
                  var data = snapshot.data['hamal'];
                  return ListView.builder(
                      itemCount: data.length,
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (BuildContext context, int index) {
                        return HamalAttendanceWidget(
                            workerId: data[index]['worker_id'],
                            name: data[index]['worker_name'],
                            wages: newWages,
                            masterAttendanceId: widget.attendanceId,
                            isPrensent: data[index]
                                    ['attendance_worker_presense']
                                .toString());
                      });
                } else if (snapshot.hasError) {
                  return const Center(
                    child: Text("Something went wrong !"),
                  );
                } else {
                  return const Center(child: LinearProgressIndicator());
                }
              },
            ),
          ]),
        ),
      ),
...rest code

小部件

 Widget build(BuildContext context) {
    return Card(
      child: Column(children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            const SizedBox(
              width: 10,
              height: 50,
            ),
            const Icon(FeatherIcons.user),
            const SizedBox(
              width: 20,
            ),
            Text(
              widget.name,
              style: const TextStyle(fontSize: 18),
            ),
          ],
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
                width: 150,
                height: 60,
                child: TextFormField(
                  // onChanged: _onChangeHandler,
                  initialValue: widget.wages.toString(),
                  decoration: const InputDecoration(
                      hintText: "Wages",
                      prefixIcon: Icon(
                        Icons.wallet,
                        color: Colors.blue,
                      )),
                )),
          ],
        )
      ]),
    );
  }

【问题讨论】:

  • 如果您有多个文本字段,则需要有一个控制器数组。通过遍历数组,您可以获得它们的特定文本。 textController.text
  • 请给我一些代码sn-p先生

标签: android ios flutter dart


【解决方案1】:

我建议您为您的应用程序使用 StateManager,例如 GetX 是一个很好的解决方案。创建一个控制器文件,如下所示:

// define this enum outside of class to handle the state of the page for load data 

enum AppState { initial, loading, loaded, error, empty, disabled }
Rx<AppState> pageState = AppState.initial.obs;

class AttendanceCntroller extends GetxController{
RxList<dynamic> dataList=RxList<dynamic>();
   @override
     void onInit() {
     //you can write other codes in here to handle data
     pageState(AppState.loading);

     dataList.value=
     SupervisorAttendanceServices.getAttendancesDetailsList(attendanceId);

     pageState(AppState.loaded);

     super.onInit();
   }
}

并在您的视图(UI)页面中,以这种方式处理它:

class AttendanceView extends GetView<AttendanceCntroller>{
  @override
   Widget body(BuildContext context) {
   // TODO: implement body
   return Obx( ()=> controller.pageState.value==AppState.loading ? const
   Center(child: LinearProgressIndicator()) :  ListView.builder(
    itemCount: controller.dataList.length,
    physics: const NeverScrollableScrollPhysics(),
    shrinkWrap: true,
    itemBuilder: (BuildContext context, int index) {
      return HamalAttendanceWidget(
          workerId: controller.dataList['worker_id'],
          name: controller.dataList['worker_name'],
          wages: newWages,
          masterAttendanceId: widget.attendanceId,
          isPrensent: controller.dataList[index]
          ['attendance_worker_presense']
              .toString());
    })
)

} }

有关更多数据,请阅读 GetX 链接并使用我的 GitHub 的 GetX 示例存储库阅读干净的架构,它使用带有依赖注入处理的 GetX 进行高级状态管理。

【讨论】:

    【解决方案2】:

    如果要在TextFormField 中预填充值,可以使用initialValuecontroller 参数。

    controller 参数的值将帮助您获取/更新TextFormField 的值。

    控制器参数见下文。

    TextEditingController controller = TextEditingController(text: 'This is text will be pre-filled in TextFormField');
    ...
    TextFormField(
      controller: controller,
    );
    

    创建这些控制器的列表或地图。

    List<TextEditingController> listOfControllers = [ controller1, controlle2,...];
    

    在 Button 的 onClick() 方法上使用 for 循环遍历此 List。

    ElevatedButton(
      onPressed: () {
        for(var controllerItem in listOfControllers) {
          print(controllerItem.text); // the value of TextFormField
        }
      },
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      相关资源
      最近更新 更多