首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用父状态小部件更新子StateFulWidget值

如何使用父状态小部件更新子StateFulWidget值
EN

Stack Overflow用户
提问于 2022-10-19 17:14:43
回答 1查看 29关注 0票数 0

我有两个独立的部件。当我单击父小部件中的按钮时,我希望更新子小部件textFormField值。我提供了下面的代码。在没有getX或提供者的情况下,我如何才能做到这一点?我想找一个解决这个问题的办法,但没有找到解决这个问题的办法。

父控件

代码语言:javascript
复制
   FutureBuilder(
              future: SupervisorAttendanceServices.getAttendancesDetailsList(
                  widget.attendanceId),
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (snapshot.hasData) {
                  var data = snapshot.data['labour'];
                  return ListView.builder(
                      itemCount: data.length,
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (BuildContext context, int index) {
                        return LabourAttendanceWidget(
                            workerId: data[index]['worker_id'],
                            masterAttendanceId: widget.attendanceId,
                            name: data[index]['worker_name'],
                            wages: data[index]['attendance_worker_wages'],
                            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());
                }
              },
            ),

子部件

代码语言:javascript
复制
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:get/get.dart';
import 'package:site_management/supervisors/screens/supervisor_attendance/controller/labour_attendance_controller.dart';
import 'package:site_management/supervisors/supervisor_services/supervisor_attendance_services.dart';

class LabourAttendanceWidget extends StatefulWidget {
  const LabourAttendanceWidget({
    Key? key,
    required this.name,
    required this.wages,
    required this.isPrensent,
    required this.workerId,
    required this.masterAttendanceId,
  }) : super(key: key);
  final int workerId;
  final int masterAttendanceId;
  final String name;
  final String wages;
  final String isPrensent;

  @override
  State<LabourAttendanceWidget> createState() => _LabourAttendanceWidgetState();
}

class _LabourAttendanceWidgetState extends State<LabourAttendanceWidget> {
  final TextEditingController _wagesController = TextEditingController();
  String _character = "";
  Timer? searchOnStoppedTyping;
  LabourAttendanceController attendanceController =
      Get.put(LabourAttendanceController());
  _onChangeHandler(value) {
    const duration = Duration(
        milliseconds:
            800); // set the duration that you want call search() after that.
    if (searchOnStoppedTyping != null) {
      setState(() => searchOnStoppedTyping?.cancel()); // clear timer
    }
    setState(() =>
        searchOnStoppedTyping = Timer(duration, () => submitWages(value)));
  }

  submitWages(value) {
    SupervisorAttendanceServices.storeWorkerWages(
        widget.workerId, value, widget.masterAttendanceId);
  }

  @override
  void initState() {
    super.initState();
    _character = widget.isPrensent;
    _wagesController.text = widget.wages;
    setState(() {});
  }

  @override
  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.spaceAround,
          children: [
            SizedBox(
                width: 150,
                height: 60,
                child: TextFormField(
                  controller: _wagesController,
                  onChanged: _onChangeHandler,
                  decoration: const InputDecoration(
                      // border: OutlineInputBorder(),
                      hintText: "Wages",
                      prefixIcon: Icon(
                        Icons.wallet,
                        color: Colors.blue,
                      )),
                )),
            Row(
              children: [
                Radio(
                  value: "P",
                  groupValue: _character,
                  fillColor:
                      MaterialStateColor.resolveWith((states) => Colors.green),
                  onChanged: (selectedValue) {
                    setState(() {
                      _character = selectedValue.toString();
                      SupervisorAttendanceServices.changeAttendance(
                              widget.workerId,
                              _character,
                              widget.masterAttendanceId)
                          .then((response) {
                        if (response == 1) {
                          return null;
                        } else {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              behavior: SnackBarBehavior.floating,
                              content: Row(
                                children: const [
                                  Icon(FeatherIcons.home),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Text("Something went wrong !"),
                                ],
                              ),
                            ),
                            // sb
                          );
                        }
                      });
                    });
                    attendanceController
                        .getAttendanceCount(widget.masterAttendanceId);
                  },
                ),
                const Text("P"),
                Radio(
                    value: "A",
                    fillColor:
                        MaterialStateColor.resolveWith((states) => Colors.red),
                    groupValue: _character,
                    onChanged: (selectedValue) {
                      setState(() {
                        _wagesController.text = "0";
                        _onChangeHandler("0");
                        _character = selectedValue.toString();
                        SupervisorAttendanceServices.changeAttendance(
                            widget.workerId,
                            _character,
                            widget.masterAttendanceId);
                      });
                      attendanceController
                          .getAttendanceCount(widget.masterAttendanceId);
                    }),
                const Text("A"),
              ],
            )
          ],
        )
      ]),
    );
  }
}
EN

回答 1

Stack Overflow用户

发布于 2022-10-19 20:02:35

首先,将LabourAttendanceWidget更改为:

代码语言:javascript
复制
class LabourAttendanceWidget extends StatefulWidget {
  const LabourAttendanceWidget({
    Key? key,
    required this.name,
    required this.wages,
    required this.isPrensent,
    required this.workerId,
    required this.masterAttendanceId,
    this.someString,
  }) : super(key: key);
  final int workerId;
  final int masterAttendanceId;
  final String name;
  final String wages;
  final String isPrensent;
  final String someString;

  @override
  State<LabourAttendanceWidget> createState() => _LabourAttendanceWidgetState();
}

然后在LabourAttendanceWidget的initState中这样做:

代码语言:javascript
复制
@override
  void initState() {
    super.initState();
    _character = widget.isPrensent;
    _wagesController.text = widget.someString ?? widget.wages;
    setState(() {});
    
  }

在您的parent小部件中,首先定义这个变量out build方法:

代码语言:javascript
复制
String? _value;

然后这样做:

代码语言:javascript
复制
return LabourAttendanceWidget(
    workerId: data[index]['worker_id'],
    masterAttendanceId: widget.attendanceId,
    name: data[index]['worker_name'],
    wages: data[index]['attendance_worker_wages'],
    someString: _value,
    isPrensent: data[index]
            ['attendance_worker_presense']
        .toString());

然后在弹出回来时填充_value,然后打电话给setstate

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74129400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档