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

Posted

技术标签:

【中文标题】Flutter:如何将变量从 StatelessWidget 传递到 StatefulWidget【英文标题】:Flutter: How to pass variables from StatelessWidget to StatefulWidget 【发布时间】:2019-08-25 00:39:45 【问题描述】:

问题是我无法将我自己的类 ForceSelection 值从另一个屏幕传递到另一个屏幕的 StatefulWidget。它在 StatelessWidget 中运行良好。我已经尝试从这个 Flutter 教程中学习: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);

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

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

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(),
    );
  

我想将 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(); 

完整的代码可以在这里找到:https://pastebin.com/nKssz42R 还有levelSelection.dart:https://pastebin.com/8QbBD0A2

【问题讨论】:

您希望从父级 -> 子级或子级 -> 父级传递吗? 我的解决方案对你有用吗? 【参考方案1】:

试试这个代码

在 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),
  );
 

游戏中测验

class PlayQuiz extends StatefulWidget 
  final ForceSelection forceSelection;

  PlayQuiz(this.forceSelection);

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

在 PlayQuizState

class PlayQuizState extends State<PlayQuiz> 
  ForceSelection forceSelection;

  PlayQuizState(ForceSelection forceSelection) 
    this.forceSelection = forceSelection;
  

【讨论】:

以上是关于Flutter:如何将变量从 StatelessWidget 传递到 StatefulWidget的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Text 变量的初始值提供给 Text Widget Flutter

如何在flutter中访问和更改来自不同文件的变量

Flutter:如何使用变量将参数传递给 Widget?

将 Future 类型化结果从函数分配给 Flutter Widget 中的变量

如何访问和更改在 FLUTTER/DART 的另一个类中声明的字符串变量的值

如何从另一个小部件类更新小部件树 - Flutter