修改Flutter Material主题Slider线条宽度

修改Flutter Material主题Slider线条宽度,第1张

在使用Flutter自带的slider组件时,发现自带的slider显示效果不理想,左边线条明显大于右边

查看Flutter源码发现,底层会对左边线条增加2个像素的宽度

解决方案:

使用自定义SliderTheme包裹Slider组件,自定义RoundedRectSliderTrackShape复现里面paint方法

  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation enableAnimation,
    required TextDirection textDirection,
    required Offset thumbCenter,
    bool isDiscrete = false,
    bool isEnabled = false,
    double additionalActiveTrackHeight = 2,
  }) 

 新建自定义Shape文件

import 'package:flutter/material.dart';

/// Created by bawomingtian on 9.12.21.
/// 修改Flutter Material 主题Slider默认滑杆左边比右边线条粗的问题
class BalanceShape extends RoundedRectSliderTrackShape {
  @override
  void paint(PaintingContext context, Offset offset,
      {RenderBox parentBox,
      SliderThemeData sliderTheme,
      Animation enableAnimation,
      TextDirection textDirection,
      Offset thumbCenter,
      bool isDiscrete = false,
      bool isEnabled = false,
      double additionalActiveTrackHeight = 0}) {
    super.paint(context, offset,
        parentBox: parentBox,
        sliderTheme: sliderTheme,
        enableAnimation: enableAnimation,
        textDirection: textDirection,
        thumbCenter: thumbCenter,
        additionalActiveTrackHeight: additionalActiveTrackHeight);
  }
}

使用SliderTheme包裹Slider

SliderTheme(
      data: SliderTheme.of(context).copyWith(trackShape: BalanceShape()),
      child: Slider(
        value: widgetItem.value,
        onChanged: (data) {},
        onChangeStart: (data) {
          print('start:$data');
        },
        onChangeEnd: (data) {
          print('end:$data');
        },
        min: widgetItem.min,
        max: widgetItem.max,
        // divisions: widgetItem.divisions,
        activeColor: ColorsUtil.hexToColor(widgetItem.activeColor ?? "#FF4CAF50"),
        inactiveColor: ColorsUtil.hexToColor(widgetItem.inactiveColor ?? "#FF9E9E9E"),
        semanticFormatterCallback: (double newValue) {
          return '${newValue.round()} dollars}';
        },
      ),
    )

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993745.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存