Flutter:如何将变量从 StatelessWidget 传递到 StatefulWidget

cha*_*ate 3 android dart flutter

问题是我无法将我自己的类 ForceSelection 值从另一个屏幕传递到另一个屏幕的 StatefulWidget。它在 StatelessWidget 中运行良好。我试图从这个颤振教程中学习:https : //flutter.dev/docs/cookbook/navigation/passing-data#4-navigate-and-pass-data-to-the-detail-screen

我在 levelSelection.dart 中有这种类

class ForceSelection {
  final String forceSelection;
  final String langSelection;

  ForceSelection(this.forceSelection, this.langSelection);
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将值传递给下一个文件 PlayQuiz.dart

Game(forceSelection: ForceSelection('maa', 'fin'))
Run Code Online (Sandbox Code Playgroud)

game.dart 看起来像这样:

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(),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我想将 ForceSelection 值传递给 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(); 
}
Run Code Online (Sandbox Code Playgroud)

整个代码可以在这里找到:https ://pastebin.com/nKssz42R 和 levelSelection.dart:https : //pastebin.com/8QbBD0A2

Man*_*nnu 9

试试这个代码

在 PlayQuiz() 中添加了 forceSelecton 参数

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),
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

在玩测验

class PlayQuiz extends StatefulWidget {
  final ForceSelection forceSelection;

  PlayQuiz(this.forceSelection);

  @override
  PlayQuizState createState() => new PlayQuizState(forceSelection); 
}
Run Code Online (Sandbox Code Playgroud)

在 PlayQuizState 中

class PlayQuizState extends State<PlayQuiz> {
  ForceSelection forceSelection;

  PlayQuizState(ForceSelection forceSelection) {
    this.forceSelection = forceSelection;
  }
}
Run Code Online (Sandbox Code Playgroud)