This content originally appeared on DEV Community and was authored by Aadarsh Kunwar
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;
});
},
)
This content originally appeared on DEV Community and was authored by Aadarsh Kunwar
Aadarsh Kunwar | Sciencx (2024-10-04T06:35:42+00:00) Slider in Flutter. Retrieved from https://www.scien.cx/2024/10/04/slider-in-flutter/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.