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

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

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

问题

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

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

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

在 "PageResult" 类中:

class PageResult extends StatefulWidget {
  final int bal; // 在构造函数中接收bal的值

  PageResult(this.bal);

  @override
  MyWidgetState createState() => MyWidgetState();
}

class MyWidgetState extends State<PageResult> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test Result"),
      ),
      body: Text('bal的值: ${widget.bal}'), // 使用widget.bal来访问bal的值
    );
  }
}

在 "MyHomePage" 类中:

ElevatedButton(
  onPressed: () {
    QuestionsList.shared.nextQuestion();
    // 其他代码...
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PageResult(bal), // 通过构造函数传递bal的值
      ),
    );
  },
  child: Text('NEXT'),
);

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

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

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

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.

import &#39;package:australia/qlist.dart&#39;;
import &#39;package:flutter/material.dart&#39;;

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {
  int _counter = 1;
  int bal = 0;
  int bad = 0;



  List&lt;Color&gt; colorsList = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];


  List&lt;String&gt; answers = [];
  @override
  void initState() {
    answers.addAll([
      QuestionsList.shared.getCurrentQuestion().correctAnswer,
      QuestionsList.shared.getCurrentQuestion().dis1,
      QuestionsList.shared.getCurrentQuestion().dis2,
      QuestionsList.shared.getCurrentQuestion().dis3,
    ]);
    answers.shuffle();
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text (&quot;Exam test&quot;),
        ),
        body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [


              Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Text(&#39;$_counter&#39;), Text(&#39;/20____&#39;), Text(&#39;$bal&#39;), Text(&#39;____&#39;), Text(&#39;$bad&#39;),
                      ],
                    ),
                  ),

                  Center(
                      child: Text(QuestionsList.shared.getCurrentQuestion().question)),
                ],
              ),


              Column(
                children: [
                  Container(
                    width: double.infinity,
                    child: Card(
                      color: colorsList[0],
                      child: InkWell(
                        child: Container(
                            margin: const EdgeInsets.all(5.0),
                            child: Text(answers[0])),
                        onTap: () {
                          if (answers[0] ==
                              QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                            colorsList[0] = Colors.green;
                            setState(() {
                              if (bad==0) {bal++;}
                              ;
                            });
                          } else {
                            colorsList[0] = Colors.red;
                            setState(() {bad++;});
                          }
                        },
                      ),
                    ),),
                  Container(
                    width: double.infinity,
                    child: Card(
                      color: colorsList[1],
                      child: InkWell(
                        child: Container(
                            margin: const EdgeInsets.all(5.0),
                            child: Text(answers[1])),
                        onTap: () {
                          if (answers[1] ==
                              QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                            colorsList[1] = Colors.green;
                            setState(() {
                              if (bad==0) {bal++;};
                            });
                          } else {
                            colorsList[1] = Colors.red;
                            setState(() {bad++;});
                          }
                        },
                      ),
                    ),),
                  Container(
                    width: double.infinity,
                    child: Card(
                      color: colorsList[2],
                      child: InkWell(
                        child: Container(
                            margin: const EdgeInsets.all(5.0),
                            child: Text(answers[2])),
                        onTap: () {
                          if (answers[2] ==
                              QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                            colorsList[2] = Colors.green;
                            setState(() {
                              if (bad==0) {bal++;};
                            });
                          } else {
                            colorsList[2] = Colors.red;
                            setState(() {bad++;});
                          }
                        },
                      ),
                    ),),
                  Container(
                    width: double.infinity,
                    child: Card(
                      color: colorsList[3],
                      child: InkWell(
                        child: Container(
                            margin: const EdgeInsets.all(5.0),
                            child: Text(answers[3])),
                        onTap: () {
                          if (answers[3] ==
                              QuestionsList.shared.getCurrentQuestion().correctAnswer) {
                            colorsList[3] = Colors.green;
                            setState(() {
                              if (bad==0) {bal++;};
                            });
                          } else {
                            colorsList[3] = Colors.red;
                            setState(() {bad++;});
                          }
                        },
                      ),
                    ),),



                  ElevatedButton(
                      onPressed: () {
                        QuestionsList.shared.nextQuestion();
                        colorsList[0] = Colors.white;
                        colorsList[1] = Colors.white;
                        colorsList[2] = Colors.white;
                        colorsList[3] = Colors.white;
                        answers.clear();
                        answers.addAll([
                          QuestionsList.shared.getCurrentQuestion().correctAnswer,
                          QuestionsList.shared.getCurrentQuestion().dis1,
                          QuestionsList.shared.getCurrentQuestion().dis2,
                          QuestionsList.shared.getCurrentQuestion().dis3,
                        ]);
                        answers.shuffle();
                        setState(() {
                          _counter++; bad=0;
                          if (_counter==20) {Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context)
                                =&gt; PageResult()

                            ),
                          );}
                        });
                      },
                      child: Text(&#39;NEXT&#39;)),
                  ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(&#39;BACK&#39;)),


                ],
              )
            ]));
  }
}

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

class PageResult extends StatefulWidget {
  
  createState() =&gt; new MyWidgetState();
}
class MyWidgetState extends State&lt;PageResult&gt; {


  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text (&quot;Test Result&quot;)
    ),
// body: Text(&#39;$bal&#39;),



    );
  }
}

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

class PageResult extends StatefulWidget {
  PageResult({required this.bal}) : super();
  final int bal;

  createState() => new MyWidgetState();
}

class MyWidgetState extends State<PageResult> {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Test Result")
      ),
      body: Center(
        child: Text('${widget.bal}'),
      )
    );
  }
}

在推送路由时使用:

Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => PageResult(bal: bal)
  )
);
英文:

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

class PageResult extends StatefulWidget {
  PageResult({required this.bal}) : super() ;
  final int bal;  

  createState() =&gt; new MyWidgetState();
}
class MyWidgetState extends State&lt;PageResult&gt; {


  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text (&quot;Test Result&quot;)
    ),
body: Center(
        child: Text(&#39;${widget.bal}&#39;),
      )
    );
  }
}

And while pushing the route

             Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context)
                                =&gt; PageResult(bal: bal)

                            ),
                          );

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:

确定