这是我参与11月更文挑战的第23天,活动详情查看:2021最后一次更文挑战。
我们聊天页面还有一个searchBar
没有实现
1. searchCell
我们在listview
再添加一个cell
,我们可以根据index
判断,我们这里一个很好的方法抽出widget
我们选中我们的代码 CMD + option + M
将选中代码提取到某个方法中
比较方便我们快速抽取,但是抽取的时候,我们用常量修饰
的话会报错变量和 const
关键字冲突.将const 关键字去掉
即可.
显示出来了,我们的index要-1
操作,itemCoun
t要+1.但是大小还是不合适和颜色样式等,我们调整一下。
我们没有考虑到背景图,我们使用最外层使用stack
进行布局,
我们在添加
点击事件
最后代码为
Widget searcheCell(){
return GestureDetector(
onTap: (){
print('点击了');
},
child: Container(
height: 44,
color: ThemeColor,
padding: EdgeInsets.all(8),
child: Stack(
alignment: Alignment.center,
children: [
Container(
decoration: BoxDecoration(
color:Colors.white,
borderRadius: BorderRadius.circular(6),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('images/放大镜b.png',color: Colors.grey,height: 15,),
Text('搜索',style: TextStyle(color: Colors.grey),),
],
),
],
)
),
);
}
复制代码
2. searchPage的搜索
我们实现搜索页以一个column
进行布局
onTap: (){
Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SearchPage()));
print('点击了');
}
复制代码
简单的实现下
这里的searchBar
我们采用Column
上下布局,上面是状态栏,下面我们使用row
布局,我们把放大镜和输入框再看成一个整体,这样再次使用row包裹
我们调整下输入框的样式,白色背景的内外的左右间距,添加取消的点击事件
我们添加输入框的选中样式和字体,我们继续实现下输入框的点击回调
_onChanged(String text){
print(text);
}
复制代码
实现输入的监听
,但是我们还需要有个清空的按钮
点击的时候清除,但是我们没有输入的时候需要隐藏
,因此我们需要监听输入框
的内容,根据内容是否展示
。
同时我们要注意当输入框内容大于0的时候显示清除按钮。
最终效果代码:
class SearchBar extends StatefulWidget {
@override
_SearchBarState createState() => _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
final TextEditingController _controller = TextEditingController();
bool isShowCancleIcon = false;
_onChanged(String text){
setState(() {
isShowCancleIcon = text.length>0;//当输入框内容大于0的时候显示清除按钮
});
print(text);
}
@override
Widget build(BuildContext context) {
return Container(
height: 84,
color: ThemeColor,
child: Column(
children: [
SizedBox(height:40),//状态栏
Container(
height: 44,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
width: screenWidth(context)-40,
height: 34,
padding: EdgeInsets.only(left: 5,right: 5),
margin: EdgeInsets.only(left: 5,right: 5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(6)
),
child: Row(
children: [
Image.asset('images/放大镜b.png',height: 20,),
Expanded(child:
TextField(
controller: _controller,
onChanged: _onChanged,
cursorColor: Colors.green,
autofocus: true,
style: TextStyle(color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w300
),
decoration: InputDecoration(
hintText: '搜索',
border: InputBorder.none,
contentPadding: EdgeInsets.only(left: 5,bottom: 10),
),
)
),//输入框
if(isShowCancleIcon)
GestureDetector(
onTap: (){
_controller.clear();
_onChanged('');
},
child: Icon(
Icons.cancel,
size: 20,
color: Colors.grey,
),
)
],
),
),//搜索框和放大镜
GestureDetector(
onTap: (){
print('返回');
Navigator.pop(context);
},
child: Text('取消'),
)
],
),
)
],
),
);
}
}
复制代码