How to Create a Slider in Flutter

The slider is an important UI component for mobile apps. It helps users to select a value from a specified range. In this blog post, let’s check how to add a slider component in flutter.

The Slider class is used to create a slider in flutter. The slider widget has attributes such as min, max, and divisions to specify the range of values. We have to use Slider as a part of the stateful widget because when the user changes the value of the slider it should be reflected immediately in the UI. The onChanged is triggered everytime the user changes the value of slider.

Slider(
    value: _currentSliderValue,
    min: 0,
    max: 100,
    divisions: 5,
    label: _currentSliderValue.round().toString(),
    onChanged: (double value) {
      setState(() {
        _currentSliderValue = value;
      });
    },
  );

Following is the complete example of flutter slider.

import 'package:flutter/material.dart';

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

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Slider Example',
      home: SliderExample(),
    );
  }
}


class SliderExample extends StatefulWidget {
  @override
  _SliderExampleState createState() => _SliderExampleState();
}

class _SliderExampleState extends State<SliderExample> {

double _currentSliderValue = 10;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter slider tutorial'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(child: Slider(
    value: _currentSliderValue,
    min: 0,
    max: 100,
    divisions: 10,
    label: _currentSliderValue.round().toString(),
    onChanged: (double value) {
      setState(() {
        _currentSliderValue = value;
      });
    },
  )
      ),
      ),   
    );
  }
}

Following is the output of the flutter slider example.

I hope you liked this flutter tutorial.

Leave a Comment

Your email address will not be published. Required fields are marked *