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

如何在Flutter中创建百分比样式的滑块

Flutter 实现百分比样式滑块

以下是实现类似参考图的百分比滑块的方案,包含完整可运行代码:

核心实现思路

  • 用Flutter内置的Slider组件作为基础,将取值范围设为0.0-1.0,对应0%到100%
  • 实时将滑块值转换为百分比文本显示
  • 通过SliderTheme自定义滑块的视觉样式,匹配参考图的设计

完整代码示例

import 'package:flutter/material.dart';

class PercentageSlider extends StatefulWidget {
  const PercentageSlider({super.key});

  @override
  State<PercentageSlider> createState() => _PercentageSliderState();
}

class _PercentageSliderState extends State<PercentageSlider> {
  // 滑块当前值,范围0.0-1.0
  double _currentSliderValue = 0.0;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        // 显示当前百分比
        Text(
          '${(_currentSliderValue * 100).round()}%',
          style: const TextStyle(
            fontSize: 22,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 16),
        // 自定义样式的滑块
        SliderTheme(
          data: SliderTheme.of(context).copyWith(
            // 激活轨道颜色
            activeTrackColor: const Color(0xFF4A90E2),
            // 未激活轨道颜色
            inactiveTrackColor: const Color(0xFFE0E0E0),
            // 滑块颜色
            thumbColor: Colors.white,
            // 滑块大小
            thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 14),
            // 滑块点击后的覆盖层颜色
            overlayColor: const Color(0xFF4A90E2).withOpacity(0.15),
            // 轨道高度
            trackHeight: 10,
            // 轨道圆角
            trackShape: const RoundedRectSliderTrackShape(),
          ),
          child: Slider(
            value: _currentSliderValue,
            min: 0.0,
            max: 1.0,
            onChanged: (newValue) {
              setState(() {
                _currentSliderValue = newValue;
              });
            },
          ),
        ),
      ],
    );
  }
}

// 测试使用
void main() {
  runApp(const MaterialApp(
    home: Scaffold(
      backgroundColor: Colors.white,
      body: Center(child: PercentageSlider()),
    ),
  ));
}

样式调整说明

  • 修改activeTrackColor和inactiveTrackColor可以自定义轨道的颜色
  • 调整thumbShape的enabledThumbRadius可以改变滑块的大小
  • 修改trackHeight可以调整轨道的粗细
  • 如果需要更复杂的样式,可以自定义SliderTrackShape或SliderThumbShape类来实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:25:38