Android – Flutter: How to pass variables from StatelessWidget to StatefulWidget

androiddartflutter

The problem is that I cannot pass the values of my own class ForceSelection values from another screen to another screen's StatefulWidget. It works fine in StatelessWidget. I have tried to learn from this flutter tutorial: https://flutter.dev/docs/cookbook/navigation/passing-data#4-navigate-and-pass-data-to-the-detail-screen

I have this kind of class in levelSelection.dart

class ForceSelection {
  final String forceSelection;
  final String langSelection;

  ForceSelection(this.forceSelection, this.langSelection);
}

I am trying to pass the values to next file PlayQuiz.dart

Game(forceSelection: ForceSelection('maa', 'fin'))

game.dart looks like this:

class Game extends StatelessWidget {
  final ForceSelection forceSelection;

  Game({Key key, @required this.forceSelection}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: forceSelection.langSelection, // TODO should work and change later
      theme: new ThemeData(
        primaryColor: Colors.white,
      ),
      home: PlayQuiz(),
    );
  }
}

And I want to pass the ForceSelection values to PlayQuiz()

class PlayQuizState extends State<PlayQuiz> {
  Game.forceSelection // <--- How can I get the value out of here?
}

class PlayQuiz extends StatefulWidget {
  @override
  PlayQuizState createState() => new PlayQuizState(); 
}

The whole code can be found here: https://pastebin.com/nKssz42R
and also levelSelection.dart: https://pastebin.com/8QbBD0A2

Best Answer

Try this code

Added forceSelecton argument in PlayQuiz()

class Game extends StatelessWidget {
final ForceSelection forceSelection;

Game({Key key, @required this.forceSelection}) : super(key: key);

@override
Widget build(BuildContext context) {
  return MaterialApp(
    title: forceSelection.langSelection, // TODO should work and change later
    theme: new ThemeData(
      primaryColor: Colors.white,
    ),
    home: PlayQuiz(forceSelection),
  );
 }
}

In Play Quiz

class PlayQuiz extends StatefulWidget {
  final ForceSelection forceSelection;

  PlayQuiz(this.forceSelection);

  @override
  PlayQuizState createState() => new PlayQuizState(forceSelection); 
}

In PlayQuizState

class PlayQuizState extends State<PlayQuiz> {
  ForceSelection forceSelection;

  PlayQuizState(ForceSelection forceSelection) {
    this.forceSelection = forceSelection;
  }
}
Related Topic