全局变量或将变量的值传递到另一个屏幕

huangapple go评论82阅读模式
英文:

Global variable or passing the value of a variable to another screen

问题

我明白你的问题。你想要将在 "MyHomePage" 类中的 "bal" 变量的值传递到 "PageResult" 类中。以下是两种可能的解决方案:

解决方案1:通过构造函数传递数据

在 "PageResult" 类中创建一个构造函数,用于接收 "bal" 变量的值。然后,在 "MyHomePage" 类中创建 "PageResult" 类的实例时,将 "bal" 的值传递给构造函数。这是一个示例:

在 "PageResult" 类中:

  1. class PageResult extends StatefulWidget {
  2. final int bal; // 在构造函数中接收bal的值
  3. PageResult(this.bal);
  4. @override
  5. MyWidgetState createState() => MyWidgetState();
  6. }
  7. class MyWidgetState extends State<PageResult> {
  8. @override
  9. Widget build(BuildContext context) {
  10. return Scaffold(
  11. appBar: AppBar(
  12. title: Text("Test Result"),
  13. ),
  14. body: Text('bal的值: ${widget.bal}'), // 使用widget.bal来访问bal的值
  15. );
  16. }
  17. }

在 "MyHomePage" 类中:

  1. ElevatedButton(
  2. onPressed: () {
  3. QuestionsList.shared.nextQuestion();
  4. // 其他代码...
  5. Navigator.push(
  6. context,
  7. MaterialPageRoute(
  8. builder: (context) => PageResult(bal), // 通过构造函数传递bal的值
  9. ),
  10. );
  11. },
  12. child: Text('NEXT'),
  13. );

解决方案2:使用全局变量

你也可以使用全局变量来存储 "bal" 的值,以便在不同类之间共享。在Dart中,你可以使用全局变量或全局状态管理库来实现这一点,例如Provider、GetX等。这里提供一个全局变量的示例:

在一个单独的Dart文件(例如globals.dart)中创建一个全局变量:

  1. int bal = 0;

然后,在 "MyHomePage" 类和 "PageResult" 类中都导入这个Dart文件,就可以访问和更新全局变量 "bal"。

请注意: 使用全局变量需要小心,因为它们可能会导致代码的维护性和可读性下降。最好的做法是使用状态管理库来处理应用程序的状态,以便更好地组织和维护代码。

英文:

I guess that the question is stupid, but for a day I can not solve this simplest problem.

In the class "MyHomePage" I have a variable "bal" which counts the correct answers.

  1. import &#39;package:australia/qlist.dart&#39;;
  2. import &#39;package:flutter/material.dart&#39;;
  3. class MyHomePage extends StatefulWidget {
  4. const MyHomePage({Key? key}) : super(key: key);
  5. @override
  6. State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
  7. }
  8. class _MyHomePageState extends State&lt;MyHomePage&gt; {
  9. int _counter = 1;
  10. int bal = 0;
  11. int bad = 0;
  12. List&lt;Color&gt; colorsList = [
  13. Colors.white,
  14. Colors.white,
  15. Colors.white,
  16. Colors.white
  17. ];
  18. List&lt;String&gt; answers = [];
  19. @override
  20. void initState() {
  21. answers.addAll([
  22. QuestionsList.shared.getCurrentQuestion().correctAnswer,
  23. QuestionsList.shared.getCurrentQuestion().dis1,
  24. QuestionsList.shared.getCurrentQuestion().dis2,
  25. QuestionsList.shared.getCurrentQuestion().dis3,
  26. ]);
  27. answers.shuffle();
  28. }
  29. @override
  30. Widget build(BuildContext context) {
  31. return Scaffold(
  32. appBar: AppBar(
  33. title: Text (&quot;Exam test&quot;),
  34. ),
  35. body: Column(
  36. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  37. children: [
  38. Column(
  39. children: [
  40. Padding(
  41. padding: const EdgeInsets.all(8.0),
  42. child: Row(
  43. children: [
  44. Text(&#39;$_counter&#39;), Text(&#39;/20____&#39;), Text(&#39;$bal&#39;), Text(&#39;____&#39;), Text(&#39;$bad&#39;),
  45. ],
  46. ),
  47. ),
  48. Center(
  49. child: Text(QuestionsList.shared.getCurrentQuestion().question)),
  50. ],
  51. ),
  52. Column(
  53. children: [
  54. Container(
  55. width: double.infinity,
  56. child: Card(
  57. color: colorsList[0],
  58. child: InkWell(
  59. child: Container(
  60. margin: const EdgeInsets.all(5.0),
  61. child: Text(answers[0])),
  62. onTap: () {
  63. if (answers[0] ==
  64. QuestionsList.shared.getCurrentQuestion().correctAnswer) {
  65. colorsList[0] = Colors.green;
  66. setState(() {
  67. if (bad==0) {bal++;}
  68. ;
  69. });
  70. } else {
  71. colorsList[0] = Colors.red;
  72. setState(() {bad++;});
  73. }
  74. },
  75. ),
  76. ),),
  77. Container(
  78. width: double.infinity,
  79. child: Card(
  80. color: colorsList[1],
  81. child: InkWell(
  82. child: Container(
  83. margin: const EdgeInsets.all(5.0),
  84. child: Text(answers[1])),
  85. onTap: () {
  86. if (answers[1] ==
  87. QuestionsList.shared.getCurrentQuestion().correctAnswer) {
  88. colorsList[1] = Colors.green;
  89. setState(() {
  90. if (bad==0) {bal++;};
  91. });
  92. } else {
  93. colorsList[1] = Colors.red;
  94. setState(() {bad++;});
  95. }
  96. },
  97. ),
  98. ),),
  99. Container(
  100. width: double.infinity,
  101. child: Card(
  102. color: colorsList[2],
  103. child: InkWell(
  104. child: Container(
  105. margin: const EdgeInsets.all(5.0),
  106. child: Text(answers[2])),
  107. onTap: () {
  108. if (answers[2] ==
  109. QuestionsList.shared.getCurrentQuestion().correctAnswer) {
  110. colorsList[2] = Colors.green;
  111. setState(() {
  112. if (bad==0) {bal++;};
  113. });
  114. } else {
  115. colorsList[2] = Colors.red;
  116. setState(() {bad++;});
  117. }
  118. },
  119. ),
  120. ),),
  121. Container(
  122. width: double.infinity,
  123. child: Card(
  124. color: colorsList[3],
  125. child: InkWell(
  126. child: Container(
  127. margin: const EdgeInsets.all(5.0),
  128. child: Text(answers[3])),
  129. onTap: () {
  130. if (answers[3] ==
  131. QuestionsList.shared.getCurrentQuestion().correctAnswer) {
  132. colorsList[3] = Colors.green;
  133. setState(() {
  134. if (bad==0) {bal++;};
  135. });
  136. } else {
  137. colorsList[3] = Colors.red;
  138. setState(() {bad++;});
  139. }
  140. },
  141. ),
  142. ),),
  143. ElevatedButton(
  144. onPressed: () {
  145. QuestionsList.shared.nextQuestion();
  146. colorsList[0] = Colors.white;
  147. colorsList[1] = Colors.white;
  148. colorsList[2] = Colors.white;
  149. colorsList[3] = Colors.white;
  150. answers.clear();
  151. answers.addAll([
  152. QuestionsList.shared.getCurrentQuestion().correctAnswer,
  153. QuestionsList.shared.getCurrentQuestion().dis1,
  154. QuestionsList.shared.getCurrentQuestion().dis2,
  155. QuestionsList.shared.getCurrentQuestion().dis3,
  156. ]);
  157. answers.shuffle();
  158. setState(() {
  159. _counter++; bad=0;
  160. if (_counter==20) {Navigator.push(
  161. context,
  162. MaterialPageRoute(
  163. builder: (context)
  164. =&gt; PageResult()
  165. ),
  166. );}
  167. });
  168. },
  169. child: Text(&#39;NEXT&#39;)),
  170. ElevatedButton(
  171. onPressed: () {
  172. Navigator.pop(context);
  173. },
  174. child: Text(&#39;BACK&#39;)),
  175. ],
  176. )
  177. ]));
  178. }
  179. }

And I need to transfer its value to the "PageResult" class.

  1. class PageResult extends StatefulWidget {
  2. createState() =&gt; new MyWidgetState();
  3. }
  4. class MyWidgetState extends State&lt;PageResult&gt; {
  5. Widget build(BuildContext context) {
  6. return Scaffold(
  7. appBar: AppBar(
  8. title: Text (&quot;Test Result&quot;)
  9. ),
  10. // body: Text(&#39;$bal&#39;),
  11. );
  12. }
  13. }

I understand that there are 2 solutions.

1. Pass data from class to class

2. Make the "bal" variable global.

But I can't find a solution in the manuals. Help please.

答案1

得分: 1

你可以通过PageResult小部件的参数化构造函数传递变量,并从State中使用引用widget.bal

  1. class PageResult extends StatefulWidget {
  2. PageResult({required this.bal}) : super();
  3. final int bal;
  4. createState() => new MyWidgetState();
  5. }
  6. class MyWidgetState extends State<PageResult> {
  7. Widget build(BuildContext context) {
  8. return Scaffold(
  9. appBar: AppBar(
  10. title: Text("Test Result")
  11. ),
  12. body: Center(
  13. child: Text('${widget.bal}'),
  14. )
  15. );
  16. }
  17. }

在推送路由时使用:

  1. Navigator.push(
  2. context,
  3. MaterialPageRoute(
  4. builder: (context) => PageResult(bal: bal)
  5. )
  6. );
英文:

You can pass the variable with a parameterised constructor of PageResult widget. And use with the reference widget.bal from State

  1. class PageResult extends StatefulWidget {
  2. PageResult({required this.bal}) : super() ;
  3. final int bal;
  4. createState() =&gt; new MyWidgetState();
  5. }
  6. class MyWidgetState extends State&lt;PageResult&gt; {
  7. Widget build(BuildContext context) {
  8. return Scaffold(
  9. appBar: AppBar(
  10. title: Text (&quot;Test Result&quot;)
  11. ),
  12. body: Center(
  13. child: Text(&#39;${widget.bal}&#39;),
  14. )
  15. );
  16. }
  17. }

And while pushing the route

  1. Navigator.push(
  2. context,
  3. MaterialPageRoute(
  4. builder: (context)
  5. =&gt; PageResult(bal: bal)
  6. ),
  7. );

huangapple
  • 本文由 发表于 2023年2月24日 15:28:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定