Flutter中如何将MyHomePage的bal变量传递至PageResult页面?
Flutter 页面间传递答题统计变量问题
我知道这个问题可能很基础,但我已经被这个最简单的问题困扰了一天。在MyHomePage类中,我有一个用于统计正确答题数的变量bal,需要将它的值传递到PageResult类中。我了解有两种解决方案:类间传值、将bal变量设为全局变量,但找不到具体实现方法。
原MyHomePage代码
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: const Text("Exam test"), ), body: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ Text('$_counter'), const Text('/20____'), Text('$bal'), const 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: const Text('NEXT')), ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('BACK')), ], ) ])); } }
原PageResult代码
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'), ); } }
解决方案一:构造函数传参(推荐)
这是Flutter中页面传参的标准方式,耦合度低,适合大多数场景。
- 修改
PageResult组件,添加参数接收
class PageResult extends StatefulWidget { // 定义接收的答题数参数 final int bal; // 构造函数,用required标记必填参数 const PageResult({Key? key, required this.bal}) : super(key: key); @override State<PageResult> createState() => MyWidgetState(); }
- 在
PageResult的状态类中访问参数
通过widget.bal即可拿到传递过来的数值:
class MyWidgetState extends State<PageResult> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("Test Result")), body: Center(child: Text("正确答题数:${widget.bal}")), ); } }
- 跳转页面时传入参数
修改MyHomePage中Navigator.push的代码,把bal传进去:
if (_counter == 20) { Navigator.push( context, MaterialPageRoute( builder: (context) => PageResult(bal: bal), // 传入bal变量 ), ); }
解决方案二:全局变量
适合小型简单项目,不推荐复杂项目使用,容易引发状态管理混乱。
- 定义全局变量
在项目的公共位置(比如新建globals.dart文件,或者在现有文件的最外层)定义全局变量:
// 全局变量,用于存储正确答题数 int globalBal = 0;
- 在
MyHomePage中使用全局变量
替换原来的局部变量bal,更新时直接修改全局变量:
class _MyHomePageState extends State<MyHomePage> { int _counter = 1; // 用全局变量替代局部变量,或者直接使用globalBal int bal = globalBal; int bad = 0; // ...其他代码不变 // 答对题时更新全局变量 setState(() { if (bad == 0) { globalBal++; bal = globalBal; // 同步到局部变量,或者直接在UI中用globalBal } }); }
- 在
PageResult中直接访问全局变量
class MyWidgetState extends State<PageResult> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text("Test Result")), body: Center(child: Text("正确答题数:$globalBal")), ); } }
内容的提问来源于stack exchange,提问作者skv500
相关产品推荐
相关产品推荐

