How to use slider widget in Flutter

In Flutter, the slider widget allows the user to select a value manually from a slider through a continuous range. This built-in widget of Flutter provides various options and modifiability to the user for selecting a feasible functionality and appearance.

To include a slider widget in your mobile application, first, ensure Flutter and Dart are installed on your machine. Then, start by creating a new Flutter project. Alternatively, you can open an existing project to incorporate a slider widget in your existing application.

Import material.dart package

In your Dart file, where you want to include the slider widget, import the necessary Flutter package named as material.dart.

As this is a built-in package, you can import it without incorporating any changes in the pubspec.yaml file or adding any dependencies. Just simply add the following lines at the top of the Dart file in which you want to use the slider widget.

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

The material.dart package provides access to a variety of built-in material design widgets, including the slider widget.

Initialize the slider widget

After importing the material.dart package, you can initialize and use the Slider widget inside the build method of your widget.

The Slider widget has several required properties that have to be initialized in order to run the Slider widget and provide its functionality in a proper way. These properties are as follows:

  • value: The initial value of the slider.

  • min: the minimum possible value of the slider.

  • max: the maximum possible value of the slider.

  • divisions: The total number of divisions on the slider.

  • onChanged: The callback functionA callback function is a function that is passed as an argument to another function and is invoked or called at a specific point in the execution of that function. is called whenever the slider value changes.

Exemplary initialization

After providing the values to all the abovementioned required properties, your initialized Slider widget should look something like this.

Slider(
value: 0.5, // The initial value of the slider
min: 0, // The minimum value of the slider
max: 1, // The maximum value of the slider
divisions: 10, // The number of divisions on the slider
onChanged: (double value) {
// This callback is called whenever the slider value changes
// Use the value parameter to update your application state
},
),
The initialized Slider widget

In this example, the slider will have a range from 0 to 1 with 10 divisions. The value parameter represents the initial value of the slider. The onChanged callback is triggered whenever the user interacts with the slider, allowing you to update your application state accordingly.

Customizing the slider appearance

After providing all the necessary parameters in the slider widget, you can customize the appearance of the slider by specifying additional properties.

Any of the following attributes can be specified according to your own preference:

  • Color

  • Track height

  • Thumb shape

  • Themes

The Slider widget provides a variety of properties that you can explore to achieve the desired visual style.

Using a slider widget in your Flutter app

import 'package:flutter/material.dart';
class SliderPage extends StatefulWidget {
  @override
  _SliderPageState createState() => _SliderPageState();
}

class _SliderPageState extends State<SliderPage> {
  double _sliderValue = 0.5;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Slider Widget Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              'Slider Value: ${_sliderValue.toStringAsFixed(1)}',
              style: TextStyle(fontSize: 18.0),
            ),
            SizedBox(height: 20.0),
            Slider(
              value: _sliderValue,
              min: 0,
              max: 50,
              divisions: 30,
              onChanged: (double value) {
                setState(() {
                  _sliderValue = value;
                });
              },
              activeColor: Colors.blue, // Sets the color of the active track
              inactiveColor: Colors.grey, // Sets the color of the inactive track
            ),
          ],
        ),
      ),
    );
  }
}
Using Slider widget

We incorporate the slider widget into the SliderPage.dart file and use _sliderValue attribute to store the value of the slider in the onChanged function.

The setState function is used in a stateful widget to set the state of an attribute. This automatically updates the attribute's value wherever it is used throughout the page.

Lastly, we can display the slider value using string interpolation using ${_sliderValue.toStringAsFixed(1)}. This rounds off the double value of the slider to one decimal place and outputs it into the Text widget.

Summary

By utilizing the Slider class from the Flutter framework, you can easily incorporate interactive and customizable sliders into your user interface. Experiment with different properties and event callbacks to use the slider to your app's specific requirements.

Copyright ©2024 Educative, Inc. All rights reserved