Ami*_*mir 5 android function callback dart flutter
我有一个数量需要在父小部件中更新。按子小部件中的 + 或 - 图标时需要更新数量。我将回调函数传递给了子无状态小部件,但它不起作用。相反,我收到一条错误消息,指出在构建期间调用了 setstate() 或 markneedsbuild() 。
这是父小部件
class Wash extends StatefulWidget {
@override
_WashState createState() => _WashState();
}
class _WashState extends State<Wash> {
int quantity = 0;
void updateQuantity(command) {
if (command == 'add') {
setState(() {
quantity++;
});
} else {
setState(() {
quantity--;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: OrderTile(
imgPath: 'shorts',
itemType: 'Shorts',
quantityCallBack: updateQuantity,
),
);
}
Run Code Online (Sandbox Code Playgroud)
这是子部件
class OrderTile extends StatelessWidget {
OrderTile({this.itemType, this.imgPath, this.quantityCallBack});
final String imgPath;
final String itemType;
final Function quantityCallBack;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(12.0),
child: Row(
children: <Widget>[
Expanded(
flex: 1,
child: CircleAvatar(
backgroundImage: AssetImage('images/${imgPath}.jpg'),
radius: 30.0,
),
),
Expanded(
flex: 3,
child: _Description(
title: itemType,
),
),
GestureDetector(
onTap: quantityCallBack('add'),
child: Icon(
Icons.add,
size: 24.0,
),
),
SizedBox(
width: 14,
),
Text('1'),
SizedBox(
width: 14,
),
GestureDetector(
onTap: quantityCallBack('remove'),
child: Icon(
Icons.remove,
size: 24.0,
),
),
],
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
我为函数回调实现做了正确的事情吗?
您在回调中以错误的方式调用回调函数onTap。改变:
onTap: quantityCallBack('add'),
Run Code Online (Sandbox Code Playgroud)
为了
onTap: () => quantityCallBack('add'),
Run Code Online (Sandbox Code Playgroud)
如果函数具有相同的类型,则只能按照您传递的方式传递函数。在这种情况下,onTap它void function()没有任何参数。
另外,您没有将更新的quantity值传递给您的Text Widget
| 归档时间: |
|
| 查看次数: |
5988 次 |
| 最近记录: |