You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中实现自定义搜索栏及下方间距布局

Flutter 顶部自定义搜索栏与间距布局实现

一、自定义搜索栏(替代默认AppBar)

从截图效果来看,顶部的搜索栏是自定义输入组件而非系统默认AppBar,实现思路是用Container包裹TextField,通过样式参数匹配视觉效果:

  • 给Container设置圆角、背景色、阴影,模拟搜索栏的悬浮质感
  • TextField内部配置搜索前缀图标、提示文字,去掉默认边框

二、间距实现

直接用SizedBox设置固定高度即可,和你观察的一致,简单直接。

完整示例代码

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.grey[100],
        body: SafeArea(
          child: Column(
            children: [
              // 自定义搜索栏
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(24),
                    boxShadow: const [
                      BoxShadow(
                        color: Colors.black12,
                        blurRadius: 4,
                        offset: Offset(0, 2),
                      )
                    ],
                  ),
                  child: const TextField(
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.search, color: Colors.grey),
                      hintText: "搜索...",
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 14),
                    ),
                  ),
                ),
              ),
              // 搜索栏下方的间距
              const SizedBox(height: 16),
              // 你的ListView.builder(示例占位)
              Expanded(
                child: ListView.builder(
                  itemCount: 20,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text("列表项 $index"),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

关键细节说明

  • 用SafeArea避免搜索栏被状态栏遮挡
  • Expanded包裹ListView.builder,确保列表占满剩余屏幕空间,避免布局溢出
  • 调整padding、borderRadius、boxShadow参数可完全匹配截图视觉效果

内容的提问来源于stack exchange,提问作者Cheems Monarch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:18:33