【发布时间】:2021-01-18 04:44:43
【问题描述】:
当我开始学习 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...)作为参数传递给另一个类,这样我就可以重用代码...你能帮帮我吗?
谢谢
【问题讨论】:
-
看看这个:flutter.dev/docs/cookbook/navigation/passing-data。尽管您可以将数据从一个小部件传递到另一个小部件,但一旦您的应用程序变得更加复杂,您将不得不使用状态管理解决方案。您不能只在五个小部件之间传递数据并期望所有小部件在数据更改时更新。我建议学习提供者而不是传递这些数据:flutter.dev/docs/development/data-and-backend/state-mgmt/…
-
“将数据从一个小部件传递到另一个小部件”从 MVC 的角度来看对我来说总是很奇怪。小部件是视图和控制器。数据应该在模型中结束,以便各种控制器可以组装他们的视图需要的东西。如果你将东西直接从一个小部件传递到另一个小部件的构造函数,那么模拟值和类以进行测试会变得更加困难。
标签: flutter dart statelesswidget