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

时间:2019-04-03 13:04:03

标签: 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);
}

我正在尝试将值传递给下一个文件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 个答案:

答案 0 :(得分:0)

尝试此代码

在PlayQuiz()中添加了forceSelecton参数

l1 = [10, 5, 2, 3, 7] # Your list
l2 = sorted(l1) # Get the sorted version of our list.

# A dictionary containing each element and a list of the indices where they are found
element_indices = {}

for index, element in  enumerate(l2):
    if element not in element_indices:
        element_indices[element] = [index] # Store the index for each element when it is sorted
    else: # We have seen this element before
        element_indices[element].append(index)

l2 = [element_indices[value].pop() for value in l1] # Change each element to its sorted equivalent index

print(l2) # [4, 2, 0, 1, 3]

播放测验中

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

在PlayQuizState中

class PlayQuiz extends StatefulWidget {
  final ForceSelection forceSelection;

  PlayQuiz(this.forceSelection);

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