Flutter 回调函数

5
我有一个需要在父部件中更新的数量。当在子小部件中按下+或-图标时,需要更新数量。我将回调函数传递给了子无状态小部件,但它并没有起作用。相反,我收到了一个错误,说在构建期间调用了`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,
        ),
   );
 }

这是子小部件

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,
        ),
      ),
    ],
  ),
);
}
}

我对函数回调实现的方式是否正确?

1个回答

6

您在onTap回调函数中以错误的方式调用了回调函数。请更改为:

onTap: quantityCallBack('add'),

对于

onTap: () => quantityCallBack('add'),

只有当两个函数类型相同时,才能以传递方式传递函数。在这种情况下,onTapvoid function(),它没有任何参数。
此外,您没有将更新的quantity值传递给您的Text Widget

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接