flutter - 如何将数据从 StatelessWidget 传递和接收到另一个?
问题描述
当我开始学习 Flutter 时,我正在使用我的知识来创建一个带有这个框架的基本计算器。我在我的应用程序中发现了一个问题......那就是:如何将参数和信息从一个小部件传递到另一个小部件?特别是从一个无状态小部件到另一个。我一直在寻找不同的地方,但我不明白我该怎么做以及它是如何工作的。
提前感谢所有可以解释我的人。
这是我正在使用的代码:
class CalcStructure extends StatelessWidget {
final List<String> rowOne = ['AC', 'Del', '%', '/'];
final List<String> rowTwo = ['7', '8', '9', '*'];
final List<String> rowThree = ['4', '5', '6', '-'];
final List<String> rowFour = ['1', '2', '3', '+'];
final List<String> rowFive = ['00', '0', '.', '='];
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height * 0.44,
color: Colors.red,
),
RowStructure(),
RowStructure(),
RowStructure(),
RowStructure(),
RowStructure(),
],
);
}
}
和 RowStructure 的类
class RowStructure extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Container(
child: FlatButton(
onPressed: () => print('Pressed'),
child: Text('AC'),
),
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.09,
),
Container(
child: FlatButton(
onPressed: () => print('Pressed'),
child: Text('AC'),
),
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.09,
),
Container(
child: FlatButton(
onPressed: () => print('Pressed'),
child: Text('AC'),
),
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.09,
),
Container(
child: FlatButton(
onPressed: () => print('Pressed'),
child: Text('AC'),
),
width: MediaQuery.of(context).size.width * 0.25,
height: MediaQuery.of(context).size.height * 0.09,
),
],
);
}
}
这个想法是将每个列表(rowOne,rowTow ...)作为参数传递给另一个类,所以我可以重用代码......你能帮帮我吗?
谢谢
解决方案
您只需通过构造函数将数据/值从一个小部件类传递到另一个:
class RowStructure extends StatelessWidget {
String text = "";
VoidCallback onTap;
RowStructure({ this.text, this.onTap });
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Container(
child: FlatButton(
onPressed: onTap,
child: Text(text),
),
推荐阅读
- ios - TableView 单元格元素上的 AddTarget 函数不起作用(发送到实例的无法识别的选择器)
- python - 使用 Python 处理加密 Zip 文件的问题
- lottie - 如何让 Lottie 从 zip 文件中播放
- javascript - ThreeJs中无尽游戏的相机位置
- node.js - 如何在谷歌云上正确托管 node.js 应用程序?
- c++ - 为什么 vsnprintf 写入的字符数与 strncpy 不同?
- python - 将二维码识别连接到 django 数据库
- substring - Swift 4 中的子字符串
- excel - 如何在 Double 上始终保留 2 位小数
- javascript - 使用外部文件重构 react 的 componentDidMount() 中的嵌套异步回调