Flutter —— 搜索框

本文介绍了如何在Flutter中创建一个搜索框,包括在ListView中添加搜索Cell,响应点击事件,创建新的SearchPage,处理搜索逻辑,显示搜索结果,并实现搜索关键字高亮。详细步骤涵盖了从界面设计到功能实现的全过程。
摘要由CSDN通过智能技术生成

在聊天界面添加一个搜索框。那么就在ListView里面添加一个cell,那么就需要itemCount里面加1。

  itemCount: _datas.length + 1,

创建一个chat package,然后将chat_page拖进来并且重新创建一个search_cell文件。
在这里插入图片描述
将ListView里面的itemBuilder的代码抽取成一个方法,然后在里面判断如果index == 0 则返回 SearchCell。这里后面需要index–,否则index就会从1开始。
在这里插入图片描述

接下来写search cell 的界面,先赋予一个高度和颜色,来看是否能显示。

 return Container(
      height: 45,
      width:  200,
      color: Colors.red,
    );

运行后看到显示了出来。
在这里插入图片描述
搜索框需要响应点击时间,所以这里需要用GestureDetector包一下,然后颜色改为weChatThemColor,里面用Stack来写。

return GestureDetector(
      child: Container(
      height: 45,
      width:  200,
      color: weChatThemColor,
       padding: EdgeInsets.all(5),
        child: Stack(
          children: [

          ],
        ),
    ),

    );

在stack里面先添加一个白底

 Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6.0),
              ),
            ),//白底

然后添加Row里面放图片和文字,为了让其居中设置row的mainAxisAlignment为MainAxisAlignment.center,而让row居中则将stack的alignment改为Alignment.center。

 child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6.0),
              ),
            ),//白底
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image(image: AssetImage('images/放大镜b.png'),width: 15,color: Colors.grey,),
                Text('   搜索',style: TextStyle(fontSize: 15,color: Colors.grey),),

            ],),

          ],
        ),

这样搜索框页面就完成了
在这里插入图片描述
接下来点进去需要到一个新的界面,那么就添加onTap,然后创建一个文件来写新页面SearchPage。

import 'package:flutter/material.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({Key? key}) : super(key: key);

  @override
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  @override
 Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          SearchBar(),
          Expanded(
            flex: 1,
            child: ListView.builder(
              itemBuilder: itemBuilder,
              itemCount: 3,
            ),
          ),
        ],
      ),
    );
  }

  Widget itemBuilder(BuildCon
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值