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

如何根据按钮尺寸动态切换按钮文本的横竖显示方向?

Flutter按钮文本根据尺寸自动切换横竖方向

要实现按钮文本根据宽高自动切换横竖显示,你可以通过LayoutBuilder获取按钮的实时尺寸约束,判断宽高比后动态调整文本方向和字体大小,以下是改造后的代码:

import 'dart:math' as math;

// 替换你原有的FittedBox部分
child: LayoutBuilder(
  builder: (context, constraints) {
    final double maxWidth = constraints.maxWidth;
    final double maxHeight = constraints.maxHeight;
    final bool isVertical = maxHeight > maxWidth;

    return FittedBox(
      fit: BoxFit.scaleDown,
      child: isVertical
          ? Transform.rotate(
              angle: -math.pi / 2,
              child: Text(
                'TEXT',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: maxHeight,
                ),
              ),
            )
          : Text(
              'TEXT',
              style: TextStyle(
                color: Colors.white,
                fontSize: maxWidth,
              ),
            ),
    );
  },
),

关键说明

  • LayoutBuilder:实时获取按钮的可用尺寸约束,确保能捕捉到按钮宽高的动态变化
  • 宽高判断逻辑:当按钮高度超过宽度时,触发纵向显示逻辑
  • Transform.rotate:通过旋转90度实现文本纵向展示,-math.pi/2的角度能让文本保持从上到下的正序阅读方向
  • 字体大小适配:纵向显示时改用maxHeight作为字体大小基准,保证文本在窄高的按钮内也能适配缩放

如果需要更精准的布局控制,也可以结合IntrinsicWidth/IntrinsicHeight调整旋转后的文本占位,但上述方案已经能覆盖大部分场景需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:27:17