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

Flutter技术问题:不同设备下保持分类列表容器尺寸恒定

解决Flutter分类列表高度随设备变化的问题

问题核心在于你使用了35.h这类相对高度单位(一般来自flutter_screenutil这类适配库),它会根据设备屏幕高度自动缩放,导致不同设备上显示高度不一致。要保持尺寸恒定,直接改用固定的密度无关像素(dp)值即可:

修改步骤

  • 把外层Container的height: 35.h替换为固定数值,比如height: 50(可根据实际视觉效果调整这个值)
  • 如果希望文字大小也保持恒定,确保Text的fontSize用固定数值(比如当前的12就是固定dp,无需改动;如果之前是12.sp这类相对单位,也换成固定数值)

修改后的完整代码

Widget categorylist() {
  return Container(
    height: 50, // 替换为固定高度,不再使用相对单位
    width: double.infinity,
    child: ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: category.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        bool isSelected = categoryText == category[index];
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
          padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
          decoration: BoxDecoration(
            color: isSelected ? primaryColor : Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: InkWell(
            onTap: () {
              categoryText = category[index];
              Provider.of<RestaurantProvider>(context, listen: false)
                  .getAll(query: searchText, category: categoryText);
            },
            child: Text(
              category[index],
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 12, // 固定文字大小,如需适配可保留sp但高度用固定值
                color: isSelected ? Colors.white : Color(0xFF4C53A5),
              ),
            ),
          ),
        );
      },
    ),
  );
}

补充说明

Flutter中的固定数值(比如50)默认是密度无关像素,会根据设备像素密度自动适配成对应物理像素,因此在不同分辨率设备上,视觉尺寸基本一致,不会出现高度忽大忽小的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:52:35