Amir
Amir

Reputation: 441

Flutter CallBack Function

I have a quantity that needs to be updated in the parent widget. Quantity needs to be updated when pressing + or - Icon in the child widget. I passed the callback function the the child stateless widget, but it is not working. Instead I get an error saying setstate() or markneedsbuild() called during build.

This is the parent widget

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

This is the child widget

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

Am I doing the right thing for the function call back implementation?

Upvotes: 5

Views: 6250

Answers (1)

pedro pimont
pedro pimont

Reputation: 3094

You're calling your callback function in the wrong way inside your onTap callback. Change:

onTap: quantityCallBack('add'),

for

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

You can only pass a function the way you passed if they have the same type. In this case the onTap is void function() it doesn't have any arguments.

Also, your not passing the updated quantity value to your Text Widget

Upvotes: 6

Related Questions