dev-resources.site
for different kinds of informations.
Slider in Flutter
Published at
10/4/2024
Categories
flutter
slider
coding
programming
Author
Aadarsh Kunwar
Main Article
Creating a slider in Flutter is straightforward using the Slider widget. Here’s a simple example that demonstrates how to implement a slider with a label showing the current value:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Slider Example')),
body: Center(
child: SliderExample(),
),
),
);
}
}
class SliderExample extends StatefulWidget {
@override
_SliderExampleState createState() => _SliderExampleState();
}
class _SliderExampleState extends State<SliderExample> {
double _sliderValue = 0.0;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Slider(
value: _sliderValue,
min: 0.0,
max: 100.0,
divisions: 10,
label: _sliderValue.round().toString(),
onChanged: (double newValue) {
setState(() {
_sliderValue = newValue;
});
},
),
Text(
'Slider Value: ${_sliderValue.round()}',
style: TextStyle(fontSize: 20),
),
],
);
}
}
Explanation
Slider Widget: The main component used to create the slider.
value: Current value of the slider.
- min: Minimum value the slider can take.
- max: Maximum value the slider can take.
- divisions: Optional. Specifies the number of discrete divisions in the slider.
- label: Displays the current value of the slider when it’s moved.
- onChanged: A callback that is called whenever the slider value changes. State Management: The slider value is managed using a stateful widget, allowing the UI to update whenever the slider value changes.
Text Widget: Displays the current value of the slider beneath it.
Customizing the Slider
You can customize the appearance of the slider further by adjusting properties like activeColor, inactiveColor, or using a SliderTheme. Here’s a quick example of how to customize the slider’s colors:
Slider(
value: _sliderValue,
min: 0.0,
max: 100.0,
divisions: 10,
label: _sliderValue.round().toString(),
activeColor: Colors.blue,
inactiveColor: Colors.grey,
onChanged: (double newValue) {
setState(() {
_sliderValue = newValue;
});
},
)
Articles
12 articles in total
What's new in Flutter 3.27
read article
Top 10 flutter interview questions
read article
Beautiful Animations with CustomPaint in Flutter
read article
Slider in Flutter
currently reading
Back after a gap because of my exams
read article
Flutter Date and Time Picker
read article
Flutter PopupMenuButton
read article
Flutter DropdownButton
read article
Flutter ListTile
read article
Aadarsh Kunwar
read article
Flutter BottomNavigationBar
read article
Flutter
read article
Featured ones: