onTap函数作为参数不起作用



我创建了一个带有Icon和onTap构造函数的自定义按钮小部件类。我想在任何点击自定义图标和自定义功能的屏幕上使用这个按钮。

class ActionButton extends StatelessWidget {
ActionButton({this.icon, this.onPress});
final FaIcon? icon;
final Function? onPress;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(18.0),
// padding: const EdgeInsets.all(0.2),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(6.0)),
// padding: const EdgeInsets.all(1.0),
child: IconButton(
onPressed: () {
onPress!;
},
icon: icon!,
color: Colors.black,
),
);
}
}

正如你所看到的,有了这个小部件,我可以在任何带有任何图标的屏幕上使用这个ActionButton,它的操作将是我作为参数传递的任何函数。

但当我在另一个页面上使用这个按钮并传递函数时,函数不会被执行:

class ProductDetailsScreen extends StatelessWidget {
final Product? product;
const ProductDetailsScreen({Key? key, this.product}) : super(key: key);
@override
Widget build(BuildContext context) {
Sizes(context).initSize();
final double _h = Sizes.screenHeight;
final double _w = Sizes.screenWidth;
final _theme = Theme.of(context);
final product = ModalRoute.of(context)!.settings.arguments as Product;
void _goBack() {
Navigator.of(context).pop();
print('the page is popped');
}
return Scaffold(
// backgroundColor: _theme.scaffoldBackgroundColor,
body: SafeArea(
child: Stack(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
ActionButton(
icon: FaIcon(
Icons.arrow_back,
),
onPress: () {
_goBack();
}),
ActionButton(
icon: FaIcon(Icons.share),
)
],
),
ListView(
scrollDirection: Axis.vertical,
children: <Widget>[
Container(
height: 60,
child: Image.asset('${product.imageSource}'),
)
],
)
],
),
),
);
}
}

_goBack()函数不工作请帮我,提前谢谢

在"产品详细信息"页面中,您需要按如下方式传递onPress参数:

ActionButton(icon:FaIcon(
Icons.arrow_back,
),onPress:_goBack)` 

在ActionButton类中

IconButton( onPressed: () { onPress!(); }, icon: icon!, color: Colors.black, ),

最新更新