英文:
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 'package:australia/qlist.dart';
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 1;
  int bal = 0;
  int bad = 0;
  List<Color> colorsList = [
    Colors.white,
    Colors.white,
    Colors.white,
    Colors.white
  ];
  List<String> 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 ("Exam test"),
        ),
        body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      children: [
                        Text('$_counter'), Text('/20____'), Text('$bal'), Text('____'), Text('$bad'),
                      ],
                    ),
                  ),
                  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)
                                => PageResult()
                            ),
                          );}
                        });
                      },
                      child: Text('NEXT')),
                  ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text('BACK')),
                ],
              )
            ]));
  }
}
And I need to transfer its value to the "PageResult" class.
class PageResult extends StatefulWidget {
  
  createState() => new MyWidgetState();
}
class MyWidgetState extends State<PageResult> {
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: Text ("Test Result")
    ),
// body: Text('$bal'),
    );
  }
}
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() => 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}'),
      )
    );
  }
}
And while pushing the route
             Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context)
                                => PageResult(bal: bal)
                            ),
                          );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论