How to access dynamic input fields values on button click in flutter

Viewed 19

I am working on an attendance application where I assign wages to the workers. I want to store all the wages given to the workers into the database. But the problem is I want to access all the given values on button click. I have no idea how it can be done in flutter. I am a beginner.

I have given all the codes and the image of what output i want.

Image of Emulator enter image description here

Here is my code...

ATTENDANCE SCREEN

...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

 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,
                      )),
                )),
          ],
        )
      ]),
    );
  }
1 Answers

I suggest you use a StateManager for your application, for example GetX is a good solution. Create a controller file like the below:

// 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();
   }
}

and in your view(UI) page, handle it in this way:

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());
    })
)

} }

for more data read the GetX link and read clean architecture with the GetX sample repository of my GitHub it have advanced management of states with GetX with dependency injection handling.

Related