简体   繁体   English

我有一个父小部件,其中包含多个子小部件,每个小部件都包含一个复选框。 如何检查父小部件中的每个复选框?

[英]I have a parent widget that contains multiple child widgets which each include a checkbox. How can I check every checkbox from the parent widget?

I have a parent widget that draws multiple child widgets using a listview.我有一个使用列表视图绘制多个子小部件的父小部件。 There is a checkbox within each of these child widgets.每个子小部件中都有一个复选框。 I am trying to implement a "select all" button in the parent widget which checks all of the children's checkboxes, but I'm having a hard time figuring out how to accomplish this.我正在尝试在父小部件中实现一个“全选”按钮,该按钮检查所有子复选框,但我很难弄清楚如何实现这一点。

Here is my parent widget:这是我的父小部件:

class OrderDisplay extends StatefulWidget {
  static const routeName = '/orderDisplay';
  //final Order order;
  //const OrderDisplay(this.order);

  @override
  OrderDisplayState createState() {
    return OrderDisplayState();
  }
}

class OrderDisplayState extends State<OrderDisplay> {
  bool preChecked = false;
  double total = 0;
  List<OrderedItem> itemsToPayFor = [];

  @override
  Widget build(BuildContext context) {
    final OrderDisplayArguments args =
        ModalRoute.of(context).settings.arguments;
    return Scaffold(
        backgroundColor: MyColors.backgroundColor,
        body: SafeArea(
            child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                physics: ScrollPhysics(),
                child: Container(
                    padding: EdgeInsets.only(top: 10),
                    child: Column(
                      children: [
                        Text(args.order.restaurantName,
                            style: MyTextStyles.headingStyle),
                        ListView.separated(
                            physics: NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            itemCount: args.order.orderedItems.length,
                            itemBuilder: (context, index) {
                              return FoodOrderNode(
                                  preChecked, args.order.orderedItems[index],
                                  onCheckedChanged: (isChecked) {
                                isChecked
                                    ? setState(() {
                                        itemsToPayFor.add(
                                            args.order.orderedItems[index]);
                                      })
                                    : setState(() {
                                        itemsToPayFor.remove(
                                            args.order.orderedItems[index]);
                                      });
                              });
                            },
                            separatorBuilder: (context, index) =>
                                MyDividers.MyDivider)
                      ],
                    )),
              ),
            ),
            MyDividers.MyDivider,
            Container(
                height: 140,
                color: MyColors.backgroundColor,
                child: Row(children: [
                  Expanded(
                      flex: 5,
                      child: Column(
                        children: [
                          Expanded(flex: 2, child: SizedBox()),
                          Expanded(
                              flex: 6,
                              child: SelectAllButton(() {
                                print("SELECT ALL");
                                setState(() {
                                  preChecked = true;
                                });
                              })), 
                          Expanded(flex: 2, child: SizedBox())
                        ],
                      )),
                  Expanded(
                      flex: 5,
                      child: Column(
                        children: [
                          Expanded(flex: 1, child: SizedBox()),
                          Expanded(
                              flex: 8,
                              child: PayNowButton(() {
                                print("PAY NOW");
                              },
                                  double.parse(itemsToPayFor
                                      .fold(0, (t, e) => t + e.itemPrice)
                                      .toStringAsFixed(
                                          2)))),
                          Expanded(flex: 1, child: SizedBox())
                        ],
                      ))
                ]))
          ],
        )));
  }
}

And here is FoodOrderNode :这是FoodOrderNode

typedef void SelectedCallback(bool isChecked);

class FoodOrderNode extends StatefulWidget {
  final bool preChecked;
  final OrderedItem item;
  final SelectedCallback onCheckedChanged;

  const FoodOrderNode(this.preChecked, this.item,
      {@required this.onCheckedChanged});

  @override
  FoodOrderNodeState createState() {
    return FoodOrderNodeState();
  }
}

class FoodOrderNodeState extends State<FoodOrderNode> {
  bool isChecked = false;
  bool isSplitSelected = false;

  @override
  Widget build(BuildContext context) {
    isChecked = widget.preChecked;
    return Container(
      height: 80,
      padding: EdgeInsets.only(left: 15, right: 15),
      decoration: BoxDecoration(
        color: MyColors.nodeBackgroundColor,
      ),
      child: Row(
        children: [
          Expanded(
              flex: 1,
              child: CircularCheckBox(
                value: isChecked,
                checkColor: Colors.white,
                activeColor: Colors.blue,
                autofocus: false,
                onChanged: (bool value) {
                  print("Change to val: $value");
                  widget.onCheckedChanged(value);
                  setState(() {
                    isChecked = value;
                  });
                },
              )),
          Expanded(
            flex: 7,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    padding: EdgeInsets.only(bottom: 5, left: 40),
                    child: Text(
                      widget.item.itemName,
                      style: TextStyle(fontSize: 18, color: Colors.black),
                      textAlign: TextAlign.left,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    )),
                Container(
                    padding: EdgeInsets.only(left: 40),
                    child: Text(
                      "\$${widget.item.itemPrice}",
                      style:
                          TextStyle(fontSize: 16, color: MyColors.labelColor),
                    ))
              ],
            ),
          ),
          Expanded(
              flex: 2,
              child: isSplitSelected
                  ? SplitButtonSelected(() {
                      setState(() {
                        isSplitSelected = false;
                      });
                    })
                  : SplitButtonUnselected(() {
                      setState(() {
                        isSplitSelected = true;
                      });
                    }))
        ],
      ),
    );
  }
}

I have tried creating a "preChecked" argument for FoodOrderNode and then using setState from the parent widget, however, that hasn't worked out.我尝试为 FoodOrderNode 创建一个“preChecked”参数,然后使用父小部件中的 setState,但是,这并没有成功。 I have also tried using keys, but I couldn't figure out how to get those working for this either.我也尝试过使用密钥,但我也不知道如何让那些为此工作。 Thank you, and let me know if you'd like any more relevant code.谢谢,如果您想要更多相关代码,请告诉我。

Just put a global checkbox above the list items and give it isAllChecked (bool) on its value so when it will be checked set the state to isAllChecked => true and then in child checkboxes check for condition if isAllChecked is true then mark as true or checked.只需在列表项上方放置一个全局复选框并将其值赋予isAllChecked (bool) 以便在检查时将 state 设置为isAllChecked => true 然后在子复选框中检查条件是否isAllChecked为 true 然后标记为true或检查。

GlobalCheckbox( onChanged(value){ setState(() { isAllChecked==value; }); } ); ChildCheckBox( value: isAllChecked? true: false )

this might help you:)这可能会帮助你:)

暂无
暂无

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

相关问题 Flutter:当小部件没有父/子关系时,如何从小部件 B 调用小部件 A 中的 function? - Flutter: How do I call a function in widget A from widget B when the widgets do not have a parent/child relationship? 如何从父小部件调用子小部件的 setState? - How can I call setState of a child widget from a parent widget? 如何将数据从子小部件传递到父小部件 - How can i pass data from a child widget to a parent widget 我可以从 dart 的子小部件中的父小部件访问变量吗? - Can I access a variable from the parent widget in a child widget in dart? 如何将整数从子小部件传递给父小部件? - How do I pass an integer from a child widget to the parent widget? 如何更改父小部件内所有子小部件的文本? - How can I change the text of all child widgets inside a parent widget? Flutter:从单个父窗口小部件控制多个子窗口小部件的状态 - Flutter: Controlling the states of multiple child widgets from a single parent widget 如何布局 GridView.count 以便小部件从 Flutter 中的父小部件顶部开始构建? - How can I layout GridView.count so the widgets start building from the top of the parent widget in Flutter? 我正在尝试将一个方法(包括 setState())从父有状态小部件传递给子无状态小部件。 但我收到以下错误 - I am trying to pass a method (which include a setState()) from a parent Stateful widget to child Stateless widget. But I am getting following errors 我想做一个复选框。 必须向 Text 小部件提供非空字符串 - I want to make a checkbox. A non-null String must be provided to a Text widget
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM