如何在有状态小部件之间传递随机数据?
Posted
技术标签:
【中文标题】如何在有状态小部件之间传递随机数据?【英文标题】:How do I pass random data between stateful widgets? 【发布时间】:2019-07-08 08:02:58 【问题描述】:我有两个有状态的类 - FirstClass 和 SecondClass。 在 FirstClass 我有两个按钮; '+' 和 '-',将接收随机数(如 1+3 或 5-2)。 然后这些随机数将在 SecondClass 中显示为文本。
您可以在互联网上找到一些关于如何将数据传递给有状态小部件的示例(这里有一些很好的链接)。
Passing Data to a Stateful Widget
Passing data to StatefulWidget and accessing it in it's state in Flutter
https://medium.com/@maksimrv/reactive-app-state-in-flutter-73f829bcf6a7 The best way to passing data between widgets in Flutter
所有这些示例的共同点是,它们假设您的数据是最终的。由于我的数字是随机的,我不能使用 final- 这就是我卡住的地方......
我的第一个问题有点不清楚,但目标是获得类似的输出 2 + 5 =_ 。用户将在文本字段中填写答案。按下按钮后,答案将传回总和并查看答案是否正确。如果答案正确 -> 执行此操作,否则 -> 执行此操作。
添加了更好的键盘。
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyHome());
class MyHome extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
title: 'passing data',
theme: ThemeData(primarySwatch: Colors.red),
home: FirstClass(),
);
class FirstClass extends StatefulWidget
@override
_FirstClassState createState() => _FirstClassState();
class _FirstClassState extends State<FirstClass>
final random = Random();
int a, b, sum;
String output;
void changeData(String buttonName)
setState(()
a = random.nextInt(10);
b = random.nextInt(10);
if (buttonName == '+')
sum = a + b;
output = '$a + $b = ';
else if (buttonName == '-')
if (a >= b)
sum = a - b;
output = '$a - $b = ';
else if (b > a)
//sum cannot be negative here
sum = b - a;
output = '$b - $a = ';
print(sum.toString());
Navigator.of(context).popUntil(ModalRoute.withName('/'));
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => SecondClass(
sum: sum,
refresh: changeData,
output: output,
)));
);
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// Text('$a + $b = $sum'),
RaisedButton(child: Text('+'), onPressed: () =>
changeData('+')),
RaisedButton(child: Text('-'), onPressed: () => changeData('-
')),
],
),
),
);
class SecondClass extends StatefulWidget
final int sum;
final String output;
final String correction;
final Function refresh;
SecondClass(this.sum, this.refresh, this.output, this.correction);
@override
_SecondClassState createState() => _SecondClassState();
class _SecondClassState extends State<SecondClass>
String enterAnswer;
String correct;
void changeAnswer()
if (enterAnswer.isNotEmpty)
if (enterAnswer == widget.sum.toString())
correct = 'Correct';
print('Correct Answer.');
else
correct = 'Wrong Answer';
print('Wrong Answer');
else
correct = 'Enter Value First';
print('Enter Value First');
@override
void initState()
super.initState();
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(widget.output),
Container(
width: 50.0,
TextField(
keyboardType: TextInputType.number,
onChanged: (val)
enterAnswer = val;
,
)),
],
),
RaisedButton(
child: Text('Check Answer'), onPressed: () =>
changeAnswer()),
Text('$correct'),
],
),
),
),
);
为什么'$correct' 不会显示为文本?我尝试在另一个项目中做同样的事情并且它成功了,那么我在这里做错了什么?
【问题讨论】:
更新了答案,请查收。 【参考方案1】:您可以通过第二类的构造函数将数据传递给第二类,并使用widget.your_data 访问它。应该使用final
因为StatefulWidget继承了Widget,标记为@immutable,所以StatefulWidget的任何子类也必须是不可变的(即所有字段都是final的)。
我根据你的问题创建了简单的用例,看看是不是你想要的:
class FirstClass extends StatefulWidget
@override
FirstClassState createState() => FirstClassState();
class FirstClassState extends State<FirstClass>
final random = Random();
int a, b, sum;
void changeData()
setState(()
a = random.nextInt(10);
b = random.nextInt(10);
sum = a + b;
);
@override
Widget build(BuildContext context)
return Scaffold(
body: SecondClass(
a: a,
b: b,
sum: sum,
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: changeData,
),
);
第二类获取数据是:
class SecondClass extends StatefulWidget
final int a;
final int b;
final int sum;
SecondClass(this.a, this.b, this.sum);
@override
_SecondClassState createState() => _SecondClassState();
class _SecondClassState extends State<SecondClass>
@override
Widget build(BuildContext context)
return Container(
child: Center(
child: Text('$widget.a + $widget.b = $widget.sum'),
),
);
在这里,如果通过 setState() 方法在第一类中更改 a、b 和 sum 值,则将重新创建所有使用这些的小部件。因此,第二类被新数据刷新。
【讨论】:
我确实得到了 sreen 2 的整数和,但我仍然无法让我的字符串“输出”(即 '$a + $b = ')出现在第二个屏幕上。 【参考方案2】:您需要callback
函数来再次获取random
值。
我假设您想在第二个 screen()
单独的类中显示 random sum value
。
这是Navigator
& Class Constructors
。
代码:
import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(MyHome());
class MyHome extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
title: 'passing data',
theme: ThemeData(primarySwatch: Colors.red),
home: FirstClass(),
);
class FirstClass extends StatefulWidget
@override
_FirstClassState createState() => _FirstClassState();
class _FirstClassState extends State<FirstClass>
final random = Random();
int a, b, sum;
String output;
void changeData(String buttonName)
setState(()
a = random.nextInt(10);
b = random.nextInt(10);
if (buttonName == '+')
sum = a + b;
output = '$a + $b = ';
else if (buttonName == '-')
if (a >= b)
sum = a - b;
output = '$a - $b = ';
else if (b > a)
//sum cannot be negative here
sum = b - a;
output = '$b - $a = ';
print(sum.toString());
Navigator.of(context).popUntil(ModalRoute.withName('/'));
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => SecondClass(
sum: sum,
refresh: changeData,
output: output,
)));
);
@override
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text('First Screen'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
// Text('$a + $b = $sum'),
RaisedButton(child: Text('+'), onPressed: () => changeData('+')),
RaisedButton(child: Text('-'), onPressed: () => changeData('-')),
],
),
),
);
class SecondClass extends StatefulWidget
final int sum;
final String output;
final Function refresh;
SecondClass(this.sum, this.refresh, this.output);
@override
_SecondClassState createState() => _SecondClassState();
class _SecondClassState extends State<SecondClass>
String enterAnswer;
@override
void initState()
super.initState();
Widget build(BuildContext context)
return Scaffold(
appBar: AppBar(
title: Text('Second Screen'),
),
body: Center(
child: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(widget.output),
Container(
width: 50.0,
child: TextField(
onChanged: (val)
enterAnswer = val;
,
)),
],
),
RaisedButton(
onPressed: ()
if (enterAnswer.isNotEmpty)
if (enterAnswer == widget.sum.toString())
print('Correct Answer.');
else
print('Wrong Answer');
else
print('Enter Value First');
,
child: Text('Check Answer'),
)
],
),
),
),
);
【讨论】:
我非常感谢。已经为此工作了数周。出于某种原因,我的 handleButtonPressed 现在给我带来了麻烦...... @J.W - 更新答案 - 请检查。 太棒了。非常感谢。以上是关于如何在有状态小部件之间传递随机数据?的主要内容,如果未能解决你的问题,请参考以下文章
在 Flutter 中使用 BLoC - 在有状态小部件与无状态小部件中的使用