简体   繁体   English

如何从 stateLessWidget 更新 StateFullWidget

[英]How to update StateFullWidget from stateLessWidget

I wanted to update the evaluateAnswer bool and rebuild the QuestionsList (stateful) widget with new value when the SubmitExamButton (which is a stateless widget) button is pressed.我想更新evaluateAnswer bool 并在SubmitExamButton (无状态小部件)按钮时使用新值重建QuestionsList (有状态)小部件。 But it always builds it with the false value which I initialized the variable with.I've tried making Body stateful widget with SubmitExamButton looking like this:但它总是使用我初始化变量的false值来构建它。我尝试使用SubmitExamButton制作Body有状态小部件,如下所示:

SubmitExamButton(
    onPress: () {
       setState(() {
           evaluateAnswer = true;
       });
    },
),

Body.dart身体.dart

class Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    bool evaluateAnswer = false;
    return Stack(

      children: [
        Padding(
          child: QuestionsList(
            evaluate: evaluateAnswer,
          ),
        ),
        Positioned(
          bottom: 0,
          child: Container(
            height: 80,
            decoration: BoxDecoration(color: Colors.white),
            width: SizeConfig.screenWidth,
            child: SubmitExamButton(
                onPress: () {
                  evaluateAnswer = true;
                },
              ),
            ),
          ),
        ),
      ],
    );
  }
}

You need to move your evaluateAnswer out into the member variables of a State class associated with a StatefulWidget.您需要将 evaluateAnswer 移出到与 StatefulWidget 关联的 State class 的成员变量中。 Then, when you setState anywhere in that build() in the State class, the Stateful widget will rebuild.然后,当您在 State class 中的 build() 中的任何位置设置状态时,有状态小部件将重建。 Sticking data as the member data of a Stateless widget does not get changes noticed by the re-build mechanism.将数据作为无状态小部件的成员数据粘贴不会让重建机制注意到更改。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM