如何在自定义_BuildingItem Widget顶层添加splash水波纹点击效果
解决方案
核心原因
Ink系列组件的水波纹效果必须绘制在最近的父级
Material组件画布上。你直接在外层包裹InkWell时,它会默认使用页面根节点Scaffold自带的Material作为绘制载体,水波纹绘制在根层级,就会被当前Widget内部的图片、浅蓝色背景等不透明元素遮挡,看起来就像显示在父Widget层级。
改造方案
把当前Widget的最外层替换为透明的Material组件,再嵌套InkWell,让水波纹直接绘制在当前Widget内部的透明Material上,就可以覆盖当前Widget的全部内容,不会被内部元素遮挡。
完整改造后代码
class _BuildingItem extends StatelessWidget { final String address; final String zip; final String zipCityName; final Image image; // 新增点击回调参数 final VoidCallback? onTap; const _BuildingItem({Key? key, required this.address, required this.zip, required this.zipCityName, required this.image, this.onTap, }): super(key: key); @override Widget build(BuildContext context) { // 最外层替换为透明Material,作为水波纹的绘制载体 return Material( color: Colors.transparent, child: InkWell( onTap: onTap, // 可自定义水波纹、高亮效果的颜色和样式 splashColor: Colors.white.withOpacity(0.3), highlightColor: Colors.white.withOpacity(0.1), child: Container( color: Colors.transparent, child: Column( children: [ ClipRect( child: image, ), Container( color: Colors.lightBlue, child: DefaultTextStyle( style: TextStyle( color: Colors.white, fontFamily: "Roboto", fontSize: 20, ), child: Column( children: [ Container( padding: EdgeInsets.only(top: 5.0), child: Text( this.address ), ), Container( padding: EdgeInsets.symmetric(vertical: 5.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( this.zip + ", " ), Text( this.zipCityName ), ], ) ), ], ), ), ), ], ), ), ), ); } }
注意事项
- 你可以根据需求调整
InkWell的splashColor、highlightColor、splashRadius等属性自定义水波纹效果 - 如果不需要水波纹覆盖图片区域,可以把
InkWell嵌套到浅蓝色Container的外层,仅给地址区域添加水波纹效果
内容的提问来源于stack exchange,提问作者Moggel
相关产品推荐
相关产品推荐

