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

Flutter中如何固定TextField?滚动时输入框随列表上移问题

实现TextField固定在页面顶部的解决方案

要让TextField固定不随列表滚动,核心是把它从滚动区域中独立出来,作为页面的固定头部,只让列表部分可滚动。修改你的build方法如下:

Widget build(BuildContext context) {
  final localStorage = GetStorage();

  return Scaffold(
    appBar: HomePageAppBar(),
    drawer: HomePageNavigationDrawer(localStorage),
    body: Column(
      children: [
        // 固定在顶部的TextField
        Padding(
          padding: const EdgeInsets.all(8.0), // 可选:添加内边距优化布局
          child: TextField(
            onChanged: (value) => _runFilter(value),
            decoration: InputDecoration(
              contentPadding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10.0),
              hintText: "Search",
              suffixIcon: const Icon(Icons.search),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20.0),
                borderSide: const BorderSide(),
              ),
            ),
          ),
        ),
        // 可滚动的列表区域
        Expanded(
          child: SingleChildScrollView(
            child: ListView.builder(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: _allUsers.length,
              itemBuilder: (context, index) => Card(
                elevation: 1,
                margin: const EdgeInsets.symmetric(vertical: 2),
                child: ListTile(
                  title: Text(_allUsers[index]['name']),
                  subtitle: Text('${_allUsers[index]["generic"]}'),
                ),
              ),
            ),
          ),
        ),
      ],
    ),
    bottomNavigationBar: const HomePageBottomNavigation(),
  );
}

关键改动说明:

  • 分离固定区域与滚动区域:将TextField从原来的SingleChildScrollView中移出,放在Column的第一个位置,这样它会固定在AppBar下方,不会随列表滚动。
  • 用Expanded适配剩余空间:给SingleChildScrollView包裹Expanded,确保列表区域能自动填充AppBar、TextField和BottomNavigationBar之外的剩余屏幕空间,避免布局溢出问题。
  • 可选优化:给TextField添加Padding,让它和页面边缘保持合适的间距,提升视觉体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:23:21