Flutter自定义滑块插件othr_slider的使用

Flutter 自定义滑块插件 othr_slider 的使用

OthrSlider 是一个高度可定制的 Flutter 滑块小部件,允许你控制滑块外观的各个方面,包括轨道、滑块指针、覆盖层和标签配置。该插件非常适合需要在 Flutter 应用程序中创建独特且视觉上吸引人的滑块的开发者。

特性

  • 自定义轨道:控制滑块轨道的大小、形状、渐变、阴影和边框。
  • 自定义指针:完全自定义指针的大小、颜色、形状、阴影和边框。
  • 自定义覆盖层:自定义指针按下时出现的覆盖层。
  • 自定义标签:自定义指针按下时出现的标签,包括支持图像和文本。
  • 响应变化:监听值的变化并相应地做出反应。

安装

othr_slider 添加到你的 pubspec.yaml 文件中:

dependencies:
    othr_slider: ^0.0.3

然后运行以下命令来安装包:

flutter pub get

使用

以下是一个基本示例,展示了如何在应用中使用 OthrSlider

import 'package:flutter/material.dart';
import 'package:othr_slider/othr_slider.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: OthrSlider(
            trackConfig: TrackConfiguration(),
            thumbConfig: ThumbConfiguration(),
            overlayConfig: OverlayConfiguration(),
            labelConfig: LabelConfiguration(),
            sliderState: SliderState(
              minValue: 0,
              maxValue: 100,
              initialValue: 20,
              onChanged: (value) {
                print('Slider value: $value');
              },
            ),
          ),
        ),
      ),
    );
  }
}

自定义配置

TrackConfiguration

使用 TrackConfiguration 控制滑块轨道的外观。

TrackConfiguration(
  height: 10.0,
  border: 1.0, // 设置边框宽度
  borderColor: Colors.black,
  borderRadius: 20.0,
  activeGradient: LinearGradient(
    colors: [Colors.blue, Colors.green],
  ), // 活动部分的渐变
  inactiveGradient: LinearGradient(
    colors: [Colors.grey, Colors.black],
  ), // 非活动部分的渐变
  displayOuterShadows: true, // 启用外阴影
  displayInnerShadows: true, // 启用内阴影
  constrainThumbInTrack: true, // 防止指针溢出轨道边缘
  innerTopShadow: const Shadow(spread: 9, offset: Offset(-5, -5), inflate: 0, radius: 30),
  innerBottomShadow: const Shadow(spread: 4, offset: Offset(5, 5), inflate: 0, radius: 30),
  outerTopShadow: const Shadow(spread: 1, offset: Offset(-2, -2), inflate: 0, radius: 30),
  outerBottomShadow: const Shadow(spread: 1, offset: Offset(2, 2), inflate: 0, radius: 30),
)
ThumbConfiguration

使用 ThumbConfiguration 控制滑块指针的外观。

ThumbConfiguration(
  radius: 15.0,
  width: 25.0,
  height: 25.0,
  colorsList: [Colors.purple, Colors.red], // 设置指针颜色
  borderColor: Colors.black,
  borderWidth: 1,
  displayInnerShadows: true, // 启用内阴影
  displayOuterShadows: true, // 启用外阴影
  autoThumbColor: true, // 指针颜色根据其在轨道上的位置计算
  innerTopShadow: const Shadow(spread: 4, offset: Offset(-5, -5), inflate: 0, radius: 20),
  innerBottomShadow: const Shadow(spread: 9, offset: Offset(5, 5), inflate: 0, radius: 20),
  outerTopShadow: const Shadow(spread: 1, offset: Offset(1, 1), inflate: 0, radius: 20),
  outerBottomShadow: const Shadow(spread: 1, offset: Offset(-1, -1), inflate: 0, radius: 20),
)
OverlayConfiguration

使用 OverlayConfiguration 自定义指针按下时出现的覆盖层。

OverlayConfiguration(
  color: Colors.yellow.withOpacity(0.4),
  radius: 20.0,
  width: 50.0,
  height: 50.0,
)
LabelConfiguration

使用 LabelConfiguration 自定义指针按下时出现的标签。

LabelConfiguration(
  useCustomLabel: true,
  showDefaultLabel: false,
  backgroundColor: Colors.black,
  textStyle: TextStyle(
    fontSize: 14.0,
    color: Colors.white,
  ), // 设置标签文字样式
  verticalOffset: 11, // 表示拇指中心和标签中心之间的偏移量
  horizontalTextOffset: -5, // 将标签文字向右移动
  width: 40,
  height: 24,
  radius: 5,
  imagePath: 'assets/label_icon.png', // 设置标签内的图像
  imageHorizontalOffset: 15, // 将图像向左移动
)
SliderState

使用 SliderState 定义全局滑块参数。

SliderState(
  minValue: 0,
  maxValue: 10,
  initialValue: 2,
  isValueRounded: true, // 显示四舍五入后的值而不是浮点值
  onChanged: (value) {
    print('Custom slider value: $value');
  },
  divisions: 10, // 固定滑块可能的值
)

示例代码

import 'package:flutter/material.dart';
import 'package:othr_slider/classes.dart';
import 'package:othr_slider/othr_slider.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'othr_slider demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Color> myColorList = const [
    Color(0xfffedac2),
    Color(0xffffe4ca),
    Color(0xffffe7c8),
    Color(0xfffee9c4),
    Color(0xfffeecc2),
    Color(0xfffeefbf),
    Color(0xfff6efc2),
    Color(0xffebefc4),
    Color(0xffe4f0c6),
    Color(0xffdcf0c9),
    Color(0xffc9eec0),
  ];

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(widget.title),
      ),
      body: Container(
        color: Colors.white,
        child: Center(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    const Text('Slider with divisions, custom label and multiple thumb colors.'),
                    const SizedBox(height: 30),
                    OthrSlider(
                      sliderState: SliderState(minValue: 0, maxValue: 10, divisions: 10),
                      trackConfig: TrackConfiguration(activeGradient: LinearGradient(colors: myColorList)),
                      thumbConfig: ThumbConfiguration(borderWidth: 1, colorsList: myColorList),
                      overlayConfig: const OverlayConfiguration(height: 40, width: 40, radius: 40),
                      labelConfig: const LabelConfiguration(),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    const Text('Slider with auto thumb colors.'),
                    const SizedBox(height: 30),
                    OthrSlider(
                      sliderState: SliderState(minValue: 0, maxValue: 100),
                      trackConfig: const TrackConfiguration(),
                      thumbConfig: const ThumbConfiguration(borderWidth: 1, autoThumbColor: true),
                      overlayConfig: const OverlayConfiguration(color: Colors.transparent),
                      labelConfig: const LabelConfiguration(),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    const Text('Slider with label image.'),
                    const SizedBox(height: 30),
                    OthrSlider(
                      sliderState: SliderState(minValue: 0, maxValue: 100, initialValue: 20),
                      trackConfig: const TrackConfiguration(
                        border: 0,
                        height: 7,
                        activeGradient: LinearGradient(colors: [Color(0xff024aff), Color(0xff024aff)]),
                        inactiveGradient: LinearGradient(colors: [Color(0xffededed), Color(0xffededed)]),
                      ),
                      thumbConfig: const ThumbConfiguration(borderColor: Color(0xff002eff), height: 15, width: 45, colorsList: [Color(0xff002eff)]),
                      overlayConfig: const OverlayConfiguration(),
                      labelConfig: const LabelConfiguration(imagePath: 'assets/eth_logo.png', imageHorizontalOffset: 15, textStyle: TextStyle(fontSize: 10), horizontalTextOffset: -5, verticalOffset: 11, backgroundColor: Colors.transparent),
                    ),
                  ],
                ),
              ),
              Container(
                color: const Color(0xff181818),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      const Text('Simple slider on dark background.', style: TextStyle(color: Colors.white)),
                      const SizedBox(height: 30),
                      OthrSlider(
                        sliderState: SliderState(minValue: 0, maxValue: 100),
                        trackConfig: const TrackConfiguration(
                          activeGradient: LinearGradient(colors: [Color(0xff0078f8), Color(0xff0078f8)]),
                          inactiveGradient: LinearGradient(colors: [Color(0xff3d3d3d), Color(0xff3d3d3d)]),
                          borderColor: Color(0xff565656),
                          constrainThumbInTrack: false,
                        ),
                        thumbConfig: const ThumbConfiguration(colorsList: [Color(0xfff2f2f2)], borderColor: Color(0xff20201f)),
                        overlayConfig: const OverlayConfiguration(),
                        labelConfig: const LabelConfiguration(useCustomLabel: false),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                color: const Color(0xffdde1e7),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      const Text('Neuemorphic slider example.'),
                      const SizedBox(height: 30),
                      OthrSlider(
                        sliderState: SliderState(minValue: 0, maxValue: 10),
                        trackConfig: const TrackConfiguration(
                          height: 20,
                          border: 0,
                          displayOuterShadows: true,
                          activeGradient: LinearGradient(colors: [Color(0xffdde1e7), Color(0xffdde1e7)]),
                          inactiveGradient: LinearGradient(colors: [Color(0xffdde1e7), Color(0xffdde1e7)]),
                        ),
                        thumbConfig: ThumbConfiguration(
                          displayInnerShadows: true,
                          displayOuterShadows: true,
                          innerTopShadow: Shadow(
                            color: const Color(0xFF5E6879).withOpacity(0.2),
                            offset: const Offset(-4, -4),
                            spread: 4,
                            radius: 20,
                          ),
                          innerBottomShadow: Shadow(
                            color: Colors.white.withOpacity(0.45),
                            spread: 4,
                            offset: const Offset(5, 5),
                            radius: 20,
                          ),
                          outerTopShadow: Shadow(
                            color: Colors.white.withOpacity(0.45),
                            spread: 1,
                            offset: const Offset(-2, -2),
                            radius: 20,
                          ),
                          outerBottomShadow: Shadow(
                            color: const Color(0xFF5E6879).withOpacity(0.2),
                            spread: 1,
                            offset: const Offset(2, 2),
                            radius: 20,
                          ),
                        ),
                        overlayConfig: const OverlayConfiguration(color: Colors.transparent),
                        labelConfig: const LabelConfiguration(useCustomLabel: false),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                color: const Color(0xff2d3139),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    children: [
                      const Text('Other neuemorphic slider example.', style: TextStyle(color: Colors.white)),
                      const SizedBox(height: 30),
                      OthrSlider(
                        sliderState: SliderState(minValue: 0, maxValue: 10),
                        trackConfig: const TrackConfiguration(
                          height: 20,
                          border: 0,
                          displayInnerShadows: true,
                          innerTopShadow: Shadow(
                            color: Color.fromRGBO(27, 28, 38, 0.4),
                            spread: 4,
                            radius: 30,
                            offset: Offset(-5, -10),
                          ),
                          innerBottomShadow: Shadow(
                            color: Color.fromRGBO(71, 75, 82, 0.45),
                            spread: 4,
                            radius: 30,
                            offset: Offset(5, 10),
                          ),
                          activeGradient: LinearGradient(colors: [Color(0xff2d3139), Color(0xff2d3139)]),
                          inactiveGradient: LinearGradient(colors: [Color(0xff2d3139), Color(0xff2d3139)]),
                        ),
                        thumbConfig: const ThumbConfiguration(
                          innerTopShadow: Shadow(
                            color: Color(0xff474b52),
                            offset: Offset(-4, -4),
                            spread: 5,
                            radius: 20,
                          ),
                          innerBottomShadow: Shadow(
                            color: Color(0xff1b1c26),
                            radius: 20,
                            spread: 9,
                            offset: Offset(5, 5),
                          ),
                          colorsList: [Color(0xff2d3139)],
                          displayInnerShadows: true,
                        ),
                        overlayConfig: const OverlayConfiguration(color: Colors.transparent),
                        labelConfig: const LabelConfiguration(useCustomLabel: false),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter自定义滑块插件othr_slider的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter自定义滑块插件othr_slider的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


othr_slider 是一个自定义的 Flutter 滑块插件,它允许开发者根据自己的需求来创建和定制滑块控件。虽然 othr_slider 不是一个官方或广泛使用的插件,但假设它是一个类似 Slider 的自定义组件,我将为你提供一个基本的示例,展示如何使用和自定义滑块控件。

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 othr_slider 插件的依赖。假设该插件已经发布到 pub.dev,你可以这样添加:

dependencies:
  flutter:
    sdk: flutter
  othr_slider: ^1.0.0  # 假设版本为1.0.0

然后运行 flutter pub get 来获取依赖。

2. 导入插件

在你的 Dart 文件中导入 othr_slider 插件:

import 'package:othr_slider/othr_slider.dart';

3. 使用 OthrSlider

假设 OthrSlider 的使用方式与 Flutter 自带的 Slider 类似,你可以这样使用它:

class MySliderPage extends StatefulWidget {
  [@override](/user/override)
  _MySliderPageState createState() => _MySliderPageState();
}

class _MySliderPageState extends State<MySliderPage> {
  double _currentValue = 0.0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Slider Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            OthrSlider(
              value: _currentValue,
              min: 0.0,
              max: 100.0,
              onChanged: (double value) {
                setState(() {
                  _currentValue = value;
                });
              },
            ),
            Text('Current Value: ${_currentValue.toStringAsFixed(1)}'),
          ],
        ),
      ),
    );
  }
}

4. 自定义 OthrSlider

假设 OthrSlider 支持一些自定义属性,比如滑块的颜色、轨道的颜色、滑块的大小等,你可以这样进行自定义:

OthrSlider(
  value: _currentValue,
  min: 0.0,
  max: 100.0,
  onChanged: (double value) {
    setState(() {
      _currentValue = value;
    });
  },
  activeTrackColor: Colors.blue,
  inactiveTrackColor: Colors.grey,
  thumbColor: Colors.red,
  thumbSize: 20.0,
);

5. 处理滑块事件

OthrSlider 可能会提供一些事件回调,比如 onChangedonChangeStartonChangeEnd 等。你可以根据需要使用这些回调来响应用户的操作:

OthrSlider(
  value: _currentValue,
  min: 0.0,
  max: 100.0,
  onChanged: (double value) {
    setState(() {
      _currentValue = value;
    });
  },
  onChangeStart: (double startValue) {
    print('Slider started at $startValue');
  },
  onChangeEnd: (double endValue) {
    print('Slider ended at $endValue');
  },
);

6. 完整示例

以下是一个完整的示例,展示了如何使用 OthrSlider 并对其进行自定义:

import 'package:flutter/material.dart';
import 'package:othr_slider/othr_slider.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Custom Slider Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MySliderPage(),
    );
  }
}

class MySliderPage extends StatefulWidget {
  [@override](/user/override)
  _MySliderPageState createState() => _MySliderPageState();
}

class _MySliderPageState extends State<MySliderPage> {
  double _currentValue = 0.0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Slider Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            OthrSlider(
              value: _currentValue,
              min: 0.0,
              max: 100.0,
              onChanged: (double value) {
                setState(() {
                  _currentValue = value;
                });
              },
              activeTrackColor: Colors.blue,
              inactiveTrackColor: Colors.grey,
              thumbColor: Colors.red,
              thumbSize: 20.0,
            ),
            SizedBox(height: 20),
            Text('Current Value: ${_currentValue.toStringAsFixed(1)}'),
          ],
        ),
      ),
    );
  }
}
回到顶部