0

I am following Angela Yu's introductory course on Flutter and extending the Quizzler project for personal challenge. At the end of a quiz, I give the user a chance to start again (show the first question screen) or to end the game (show a "goodbye" screen). I have this basic structure:

class _QuizPageState extends State<QuizPage> {
  Widget selectContents() {
    // getGameState() reads a boolean flag; false means user is quitting
    // but a change from true to false is only detected
    // when main.dart is saved in the IDE.
    print('Game State: --------> ${quizBrain.getGameState()}');
    return (quizBrain.getGameState()) ? QuizContents() : GoodbyeScreen();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: selectContents(),
    );
  }
}

This does not work. When the user opts to end the quiz, the choice does not register and the last screen of QuizContents remains visible. When I go into the IDE and simply save main.dart, the flag somehow updates (and the print statement now reports the right value for the game state) and GoodbyeScreen() appears in the simulator.

This problem has many versions and suggestions on StackOverflow. I have tried all the solutions here and here, including:

  • putting the ternary operator directly as a child to the Container
  • using a Builder widget instead of the Container
  • putting the selectContents() function inside and outside the build() method of _QuizPageState
  • using if/else cascade inside an anonymous function as a child to the Container
  • ...etc

None of these have worked and the behaviour remains the same.

daedalus
  • 10,873
  • 5
  • 50
  • 71

1 Answers1

1

This is a state management problem. You haven't included where quizBrain is saved, but if it's in _QuizPageState, calling setState when you change boolean flag should fix the problem, otherwise the widget is never rebuilt.

The reason saving in your IDE updates the value is because Flutter performs a hot reload and rebuilds some (maybe all) widgets.

There are many other state management methods, apart from setState. An interesting read is Simple app state management. Your choice depends on the complexity of your app, but I would imagine in this case, setState should be enough.

David
  • 1,688
  • 1
  • 11
  • 21