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

Flutter中如何实现拖动滑块动态调整面板内字体大小的功能

Flutter 双面板拖动+字体动态调整实现方案

你可以通过状态监听拖动偏移量,同时关联面板宽度和文本字体大小实现需求,对应UI效果参考:
设计图1

完整实现步骤

  • 第一步:用StatefulWidget维护全局拖动比例状态,默认设置为0.5(左右面板各占一半宽度),同时限制比例取值范围避免面板被过度压缩
    double _splitRatio = 0.5;
    final double _minRatio = 0.2;
    final double _maxRatio = 0.8;
    final double _dragBarWidth = 4; // 中间拖动条的宽度
    
  • 第二步:构建布局结构,用Row嵌套左面板、拖动条、右面板三个组件,通过_splitRatio动态计算两个面板的宽度
    @override
    Widget build(BuildContext context) {
      final screenWidth = MediaQuery.of(context).size.width;
      final leftPanelWidth = screenWidth * _splitRatio - _dragBarWidth / 2;
      final rightPanelWidth = screenWidth * (1 - _splitRatio) - _dragBarWidth / 2;
      return Scaffold(
        body: Row(
          children: [
            // 左面板
            SizedBox(
              width: leftPanelWidth,
              child: Center(
                child: Text(
                  "左侧面板内容",
                  // 字体大小和左面板占比正相关,比例越大字体越大,基础字号14,最大可到24可自行调整
                  style: TextStyle(fontSize: 14 + (_splitRatio - _minRatio) * 20),
                ),
              ),
            ),
            // 中间拖动条
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onHorizontalDragUpdate: (details) {
                // 计算拖动偏移量更新比例
                final newRatio = _splitRatio + details.delta.dx / screenWidth;
                setState(() {
                  _splitRatio = newRatio.clamp(_minRatio, _maxRatio);
                });
              },
              child: Container(
                width: _dragBarWidth,
                color: Colors.grey,
              ),
            ),
            // 右面板
            SizedBox(
              width: rightPanelWidth,
              child: Center(
                child: Text(
                  "右侧面板内容",
                  // 字体大小和右面板占比正相关
                  style: TextStyle(fontSize: 14 + ((1 - _splitRatio) - _minRatio) * 20),
                ),
              ),
            )
          ],
        ),
      );
    }
    
  • 第三步:自定义适配调整,你可以根据设计需求修改字号的计算系数、拖动条样式、面板最小/最大占比阈值;如果面板内有多个文本组件,可以把计算好的字号通过DefaultTextStyle统一设置给整个面板的子节点,无需逐个给Text组件传style参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 03:15:04