Home > Back-end >  How to pass function to class attribute in flutter?
How to pass function to class attribute in flutter?

Time:08-20

I am trying to assign a function to an class attribute. HOw can i assign that value to that class' attribue.

 return MyCartListItem(
                    cartName: cartList[index]['english_name'],
                    cartQuantity: 2,
                    cartImage: path   img,
                    cartPrice: cartList[index]['mrp'].toString(),
                    cartIndex: cartList[index],
                    onItemRemoved: ?? ,
                  //trying to assing function here
                  );
 const MyCartListItem(
      {Key? key,
    ...
      required this.onItemRemoved,
      required this.onItemRemoved(index)})
      : super(key: key);
  final String cartName;
  final int cartQuantity;
  final String cartImage;
  final String cartPrice;
  final int cartIndex;
  final Function onItemRemoved;
// func here

  @override
  State<MyCartListItem> createState() => _MyCartListItemState();
}

CodePudding user response:

onItemRemoved(){

}

return MyCartListItem(
        cartName: cartList[index]['english_name'],
        cartQuantity: 2,
        cartImage: path   img,
        cartPrice: cartList[index]['mrp'].toString(),
        cartIndex: cartList[index],
        onItemRemoved: onItemRemoved ,
      //trying to assing function here
      );

CodePudding user response:

so you have a function like this:

onTap({required String message}){
   print(message);
}

in your class pass function argument like this:

class ClassTest extends StatelessWidget {
  final Function({required String message}) onTap;
  const ClassTest({Key? key, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: ()=>onTap(message: 'your mesage'),
      child: Container(),
    );
  }
}
  • Related