Flutter交互式滑块插件interactive_slider的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter交互式滑块插件interactive_slider的使用

描述

interactive_slider 是一个受苹果音乐应用程序音量滑块启发的连续或分段滑块小部件。此小部件几乎无需设置即可使用,但仍然可以完全自定义!

Slider being used Slider being used with shapes Slider being used with colors

功能特性

  • 内置填充方便使用
  • 可调整大小过渡效果
  • 使用任何小部件作为开始/结束图标和中心标签
  • 使用任何过渡持续时间和曲线
  • 为进度条提供任何形状边界
  • 使用归一化的进度值或轻松提供最小值/最大值以自动转换
  • 使用滑块进度动画开始和结束图标
  • 使用渐变颜色着色滑块的进度
  • 创建任意数量的离散段来滑动

开始使用

添加依赖项

在您的 pubspec.yaml 文件中添加以下内容:

dependencies:
  interactive_slider: ^0.5.0

导入包

然后在 Dart 文件中导入:

import 'package:interactive_slider/interactive_slider.dart';

使用方法

以下是一个简单的示例代码,演示了如何使用 InteractiveSlider 小部件:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:interactive_slider/interactive_slider.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          brightness: Brightness.dark,
          seedColor: Colors.deepPurple,
        ),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Interactive Slider'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _controller = InteractiveSliderController(0.5);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: ListView(
        padding: const EdgeInsets.symmetric(vertical: 16),
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 28),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ElevatedButton(
                  onPressed: () => _controller.value = 0.0,
                  child: const Text('Min'),
                ),
                ValueListenableBuilder<double>(
                  valueListenable: _controller,
                  builder: (context, progress, child) =>
                      Text(progress.toStringAsFixed(3)),
                ),
                ElevatedButton(
                  onPressed: () => _controller.value = 1.0,
                  child: const Text('Max'),
                ),
              ],
            ),
          ),
          InteractiveSlider(
            controller: _controller,
            startIcon: const Icon(CupertinoIcons.minus_circle),
            endIcon: const Icon(CupertinoIcons.add_circled),
            onChanged: (value) {
              // This callback runs repeatedly for every update
            },
            onProgressUpdated: (value) {
              // This callback runs once when the user finishes updating the slider
            },
          ),
          const Divider(),
          const InteractiveSlider(
            enabled: true,
            startIcon: Icon(CupertinoIcons.volume_down),
            endIcon: Icon(CupertinoIcons.volume_up),
          ),
          const InteractiveSlider(
            iconPosition: IconPosition.below,
            startIcon: Icon(CupertinoIcons.volume_down),
            endIcon: Icon(CupertinoIcons.volume_up),
            centerIcon: Text('Center'),
          ),
          const InteractiveSlider(
            iconPosition: IconPosition.inside,
            startIcon: Icon(CupertinoIcons.volume_down),
            endIcon: Icon(CupertinoIcons.volume_up),
            centerIcon: Text('Center'),
            unfocusedHeight: 40,
            focusedHeight: 50,
            iconGap: 16,
          ),
          const Divider(),
          const InteractiveSlider(
            unfocusedHeight: 30,
            focusedHeight: 40,
            numberOfSegments: 7,
          ),
          const InteractiveSlider(
            unfocusedHeight: 30,
            focusedHeight: 40,
            shapeBorder: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8)),
            ),
          ),
          const InteractiveSlider(
            unfocusedHeight: 30,
            focusedHeight: 40,
            shapeBorder: BeveledRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8)),
            ),
          ),
          const Divider(),
          const InteractiveSlider(
            unfocusedOpacity: 1,
            unfocusedHeight: 30,
            focusedHeight: 40,
            foregroundColor: Colors.deepPurple,
          ),
          const InteractiveSlider(
            unfocusedOpacity: 1,
            unfocusedHeight: 30,
            focusedHeight: 40,
            gradient: LinearGradient(colors: [Colors.green, Colors.red]),
          ),
          const InteractiveSlider(
            unfocusedOpacity: 1,
            unfocusedHeight: 30,
            focusedHeight: 40,
            gradient: LinearGradient(colors: [Colors.green, Colors.red]),
            gradientSize: GradientSize.progressWidth,
          ),
        ],
      ),
    );
  }
}

这个示例展示了如何创建一个具有不同配置的 InteractiveSlider 滑块,并且通过 InteractiveSliderController 控制滑块的状态。你可以根据需要修改这些属性来自定义你的滑块。

如果您遇到任何问题或有改进建议,请随时通过 GitHub 提交问题或拉取请求。


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

1 回复

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


当然,下面是一个关于如何在Flutter中使用interactive_slider插件的示例代码。这个插件允许你创建一个交互式滑块,用于选择范围值或单个值。请注意,你可能需要先在你的pubspec.yaml文件中添加interactive_slider依赖项:

dependencies:
  flutter:
    sdk: flutter
  interactive_slider: ^最新版本号  # 请替换为实际可用的最新版本号

然后,运行flutter pub get来安装依赖。

以下是使用interactive_slider插件的示例代码:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Interactive Slider Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // 滑块的值
  double sliderValue = 50.0;
  RangeValues sliderRangeValues = RangeValues(20.0, 80.0);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Interactive Slider Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('单个滑块示例:'),
            InteractiveSlider(
              min: 0.0,
              max: 100.0,
              values: [sliderValue],
              onChanged: (values) {
                setState(() {
                  sliderValue = values[0];
                });
              },
              onValuesChanged: (values) {
                setState(() {
                  sliderValue = values[0];
                });
              },
            ),
            SizedBox(height: 20.0),
            Text('范围滑块示例:'),
            InteractiveRangeSlider(
              min: 0.0,
              max: 100.0,
              values: sliderRangeValues,
              onChanged: (values) {
                setState(() {
                  sliderRangeValues = values;
                });
              },
              onValuesChanged: (values) {
                setState(() {
                  sliderRangeValues = values;
                });
              },
            ),
            SizedBox(height: 20.0),
            Text('当前值: ${sliderValue.roundToDouble()}'),
            SizedBox(height: 10.0),
            Text('当前范围值: ${sliderRangeValues.start.roundToDouble()} - ${sliderRangeValues.end.roundToDouble()}'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们展示了如何使用InteractiveSliderInteractiveRangeSliderInteractiveSlider用于选择单个值,而InteractiveRangeSlider用于选择范围值。滑块的值通过values属性进行绑定,并在滑块值变化时通过onChangedonValuesChanged回调更新状态。

注意:

  • onChanged回调在拖动滑块时触发。
  • onValuesChanged回调在滑块值最终确定时触发(例如,当释放滑块时)。

你可以根据需求调整滑块的minmax和初始values,以及滑块的外观样式。希望这个示例对你有帮助!

回到顶部