biniyam112
biniyam112

Reputation: 1182

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

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

Body.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;
                },
              ),
            ),
          ),
        ),
      ],
    );
  }
}

Upvotes: 0

Views: 59

Answers (1)

Randal Schwartz
Randal Schwartz

Reputation: 44066

You need to move your evaluateAnswer out into the member variables of a State class associated with a StatefulWidget. Then, when you setState anywhere in that build() in the State class, the Stateful widget will rebuild. Sticking data as the member data of a Stateless widget does not get changes noticed by the re-build mechanism.

Upvotes: 1

Related Questions