【问题标题】:Flutter CallBack Function颤振回调函数
【发布时间】:2020-07-10 14:14:13
【问题描述】:

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

我是否为函数回调实现做了正确的事情?

【问题讨论】:

    标签: android function flutter dart callback


    【解决方案1】:

    您在 onTap 回调中以错误的方式调用回调函数。变化:

    onTap: quantityCallBack('add'),
    

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

    如果它们具有相同的类型,您只能以您传递的方式传递一个函数。在这种情况下,onTapvoid function(),它没有任何参数。

    另外,您没有将更新后的 quantity 值传递给您的 Text Widget

    【讨论】:

      猜你喜欢
      • 2020-08-02
      • 2021-11-27
      • 1970-01-01
      • 2022-01-11
      • 2020-02-07
      • 2020-12-08
      • 2021-06-18
      • 2021-02-17
      • 2020-07-28
      相关资源
      最近更新 更多