Flutter实现自定义筛选框
一、首先自定义筛选框的按钮视图,布局很简单,一个listView就可以搞定。 1、在数据model中添加了一个selectedModel属性,用来记录当前已选择的筛选项(目前仅支持单选)。 2、当按钮数量小于3个时,按钮最大宽度为屏幕宽度的1/3;小于屏幕宽度时,则为屏幕宽度/按钮数量。 具体代码如下:
var text = model.selectedFilterModel != null
? model.selectedFilterModel.dictValue
: model.name ?? "";
return Container(
padding: EdgeInsets.symmetric(horizontal: 20),
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width /
(widget.dataList.length > 3 ? 3 : widget.dataList.length),
maxHeight: widget.viewHeight),
color: Colors.white,
child: InkWell(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: widget.textSize,
color: model.isSelected
? widget.textSelectColor
: widget.textColor),
),
SizedBox(
width: 4,
),
model.isSelected == true
? Icon(Icons.keyboard_arrow_down,
color: widget.textSelectColor)
: Icon(Icons.keyboard_arrow_up, color: widget.textColor),
],
),
onTap: () {
setState(() {
if (_selectModel != null && _selectModel != model) {
_selectModel.isSelected = false;
}
model.isSelected = !model.isSelected;
_selectModel = model;
});
}));
二、定义筛选数据展示列表视图。 首先在剩余视图上定义一个背景黑色透明的遮罩层,然后在这层Container上展示listView,listView展示的数据为筛选的具体数据内容。Visibility控制整体视图是否可见,具体代码如下:
visible:
Provider.of<FilterModelProvider>(context).isShowFilterOptionsView ??
false,
child: GestureDetector(
onTap: () {
Provider.of<FilterModelProvider>(context, listen: false)
.hideFilterOptionsView();
},
child: Container(
color: Colors.black54,
child: Container(
margin: EdgeInsets.only(
bottom: SizeFit.screenHeight -
widget.filterButtonViewHeight -
SizeFit.appBarHeight -
listViewHeight +
animation.value),
color: Colors.white,
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: _dataList.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Container(
height: widget.listHeight,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
// crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_dataList[index].dictValue,
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(
fontSize: 16,
color: Colors.black87,
fontWeight: FontWeight.normal),
),
Divider(
height: 1,
indent: 1,
)
],
),
),
onTap: () {
Provider.of<FilterModelProvider>(context, listen: false)
.selectFilterOption(_dataList[index]);
},
);
}),
),
),
),
);
大致思路就是以上两点,有问题欢迎留言评论。后期会加入动画效果,也会贴上具体项目链接,敬请期待!
转载自:https://juejin.cn/post/6983971330064384037