简体   繁体   English

如何在 flutter 中将 set state 值更改从父窗口小部件传递给子窗口小部件?

[英]How to pass set state value changes from parent to child widget in flutter?

I've declared an int 'k' and I'm changing it's value from user's input using set state function. The value changes of 'k' are reflected on Nutrition function. But when passing value of 'k' to checkbbox function it is always 2(initial value).我已经声明了一个 int 'k',我正在使用集合 state function 更改用户输入的值。'k' 的值更改反映在营养 function 上。但是当将 'k' 的值传递给复选框 function 时,它是始终为 2(初始值)。

Basically set state changes are not passed to checkbox even though the Nutrition widget is rebuilding.基本上设置 state 更改不会传递到复选框,即使营养小部件正在重建。

    class Nutrition extends StatefulWidget {
      @override
      _Nutrition createState() => _Nutrition();
    }
    
    class _Nutrition extends State<Nutrition> {
      DateTime now = DateTime.now().toLocal();
      int k = 2;

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('CqMyOE via Nutrition'),
      ),
      body: SingleChildScrollView(
        child: Container(
          color: Colors.grey[200],
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  FlatButton(
                    onPressed: () {
                      setState(() {
                        k = 0;
                      });
                    },
                    child: Text(
                      DateFormat('dd-MMM').format(now),
                    ),
                    color: (k == 0) ? Colors.greenAccent : Colors.grey,
                  ),
                  FlatButton(
                    onPressed: () {
                      setState(() {
                        k = 1;
                      });
                    },
                    child: Text(
                      DateFormat('dd-MMM')
                          .format(now.subtract(new Duration(days: 1))),
                    ),
                    color: (k == 1) ? Colors.greenAccent : Colors.grey,
                  ),
                  FlatButton(
                    onPressed: () {
                      setState(() {
                        k = 2;
                      });
                    },
                    child: Text(
                      DateFormat('dd-MMM')
                          .format(now.subtract(new Duration(days: 2))),
                    ),
                    color: (k == 2) ? Colors.greenAccent : Colors.grey,
                  ),
                  FlatButton(
                    onPressed: () {
                      setState(() {
                        k = 3;
                      });
                    },
                    child: Text(
                      DateFormat('dd-MMM')
                          .format(now.subtract(new Duration(days: 3))),
                    ),
                    color: (k == 3) ? Colors.greenAccent : Colors.grey,
                  ),
                ],
              ),
              Card(
                child: Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(8, 16, 8, 16),
                        child: Text('Salt awareness' + k.toString()),
                      ),
                    ),
                    Expanded(
                      child: Row(
                        children: [
                          CheckBox(
                            10,
                            nutritionDB.get(curDate).record[10] ?? '0',
                            k,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
             ]
           )
         )
       )
     )
}

class CheckBox extends StatefulWidget {
  final int index;
  final String value;
  // final String date;
  final int k;
  CheckBox(this.index, this.value, this.k);
  @override
  State<StatefulWidget> createState() =>
      _CheckBox(index, value == '1' ? true : false, k);
}

class _CheckBox extends State<CheckBox> {
  int index;
  bool checked;
  // String date;
  int k;
  _CheckBox(this.index, this.checked, this.k);

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: Icon(
        checked ? Icons.check : Icons.clear,
      ),
      color: checked ? Colors.green : Colors.red,
      onPressed: () {
        final nutritionDB = Hive.box<NutritionData>('NutritionDB');

        List<String> temp = nutritionDB.get(day3).record;
        temp[index] = !checked ? '1' : '0';
        NutritionData temp1 = new NutritionData(temp);
        nutritionDB.put(day3, temp1);
        setState(() {
          print(k);
          checked = !checked;
        });
      },
    );
  }
}

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
For demo purpose, I add k value before IconButton出于演示目的,我在IconButton之前添加了k
You can in didUpdateWidget reset k = widget.k;你可以在didUpdateWidget中 reset k = widget.k;
code snippet代码片段

class _CheckBox extends State<CheckBox> {
  ...

  @override
  void didUpdateWidget(covariant CheckBox oldWidget) {
    if (oldWidget.k != widget.k) {
      k = widget.k;
    }

    super.didUpdateWidget(oldWidget);
  }

working demo工作演示

在此处输入图像描述

full code完整代码

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class Nutrition extends StatefulWidget {
  @override
  _Nutrition createState() => _Nutrition();
}

class _Nutrition extends State<Nutrition> {
  DateTime now = DateTime.now().toLocal();
  int k = 2;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('CqMyOE via Nutrition'),
        ),
        body: SingleChildScrollView(
            child: Container(
                color: Colors.grey[200],
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          FlatButton(
                            onPressed: () {
                              setState(() {
                                k = 0;
                              });
                            },
                            child: Text(
                              DateFormat('dd-MMM').format(now),
                            ),
                            color: (k == 0) ? Colors.greenAccent : Colors.grey,
                          ),
                          FlatButton(
                            onPressed: () {
                              setState(() {
                                k = 1;
                              });
                            },
                            child: Text(
                              DateFormat('dd-MMM')
                                  .format(now.subtract(new Duration(days: 1))),
                            ),
                            color: (k == 1) ? Colors.greenAccent : Colors.grey,
                          ),
                          FlatButton(
                            onPressed: () {
                              setState(() {
                                k = 2;
                              });
                            },
                            child: Text(
                              DateFormat('dd-MMM')
                                  .format(now.subtract(new Duration(days: 2))),
                            ),
                            color: (k == 2) ? Colors.greenAccent : Colors.grey,
                          ),
                          FlatButton(
                            onPressed: () {
                              setState(() {
                                k = 3;
                              });
                            },
                            child: Text(
                              DateFormat('dd-MMM')
                                  .format(now.subtract(new Duration(days: 3))),
                            ),
                            color: (k == 3) ? Colors.greenAccent : Colors.grey,
                          ),
                        ],
                      ),
                      Card(
                        child: Row(
                          children: [
                            Expanded(
                              flex: 1,
                              child: Padding(
                                padding:
                                    const EdgeInsets.fromLTRB(8, 16, 8, 16),
                                child: Text('Salt awareness' + k.toString()),
                              ),
                            ),
                            Expanded(
                              child: Row(
                                children: [
                                  CheckBox(
                                    10,
                                    "nutritionDB.get(curDate).record[10]" ??
                                        '0',
                                    k,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ]))));
  }
}

class CheckBox extends StatefulWidget {
  final int index;
  final String value;
  // final String date;
  final int k;
  CheckBox(this.index, this.value, this.k);
  @override
  State<StatefulWidget> createState() =>
      _CheckBox(index, value == '1' ? true : false, k);
}

class _CheckBox extends State<CheckBox> {
  int index;
  bool checked;
  // String date;
  int k;
  _CheckBox(this.index, this.checked, this.k);

  @override
  void didUpdateWidget(covariant CheckBox oldWidget) {
    if (oldWidget.k != widget.k) {
      k = widget.k;
    }

    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text("k $k"),
        IconButton(
          icon: Icon(
            checked ? Icons.check : Icons.clear,
          ),
          color: checked ? Colors.green : Colors.red,
          onPressed: () {
            //final nutritionDB = Hive.box<NutritionData>('NutritionDB');

            //List<String> temp = nutritionDB.get(day3).record;
            //temp[index] = !checked ? '1' : '0';
            //NutritionData temp1 = new NutritionData(temp);
            //nutritionDB.put(day3, temp1);
            setState(() {
              print(k);
              checked = !checked;
            });
          },
        ),
      ],
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Nutrition(),
    );
  }
}

暂无
暂无

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

相关问题 Flutter:从子小部件设置父小部件状态 - Flutter: set parent widget state from child widget Flutter:如何从子小部件更新子(和父)小部件的 state(父小部件得到更新,子小部件没有) - Flutter: How to update state of child (and parent) widget from child widget (parent widget gets update, child does not) 如何将数据从子状态小部件传递到 Flutter 中的父小部件 - How to pass data from a child Stateful widget to Parent Widget in Flutter 如何从 flutter 中的父小部件访问所有孩子的 state? - How to access all of child's state from Parent Widget in flutter? 如何从其子 Widget 更新 Parent Widget 的状态,同时在 Flutter 中更新 Child 的状态? - How to update the state of Parent Widget from its Child Widget while also updating the Child's state in Flutter? Flutter - 如何将 focusNode 从 Parent 设置为 Child 小部件? - Flutter - How to set focusNode from Parent to Child widget? Flutter:如何设置父窗口小部件的 state - Flutter: How to set state of parent widget 如何将父小部件的高度传递给 flutter 中的子小部件? - How to pass the height of parent widget to child widget in flutter? Flutter - 如何从子小部件调用父小部件函数,同时还使用变量保持状态? - Flutter - How do I call a Parent widget function from child widget while also maintaining the state with a variable? 在 Flutter 中设置 Parent Widget 的 State - Set State of Parent Widget in Flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM