This article walks you through a complete example of using CupertinoSlider, an iOS-style widget in Flutter that lets the user select from a range of number values.
Table of Contents
A Prefatory Note
The CupertinoSlider class requires 2 parameters:Advertisements
- value: The current value of the slider (type: double)
- onChanged: A function called whenever the user move the sliderÂ’s thumb (some people call it cursor) and returns the new selected value.
You can find more information about the constructor and properties in the official docs. If you want to see the code in action and move fast instead of reading the boring text, check the example below.
The Example
This example only uses the Cupertino library and the material library isnÂ’t imported.
Preview
What weÂ’re going to build is a sample app that contains a slider and a text widget in the center of the screen. When the slider changes, the selected value will be immediately reflected in the text widget, as shown below:
The Code
// main.dart
import 'package:flutter/cupertino.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoApp(
// Remove the debug banner
debugShowCheckedModeBanner: false,
title: 'Kindacode.com',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double _currentValue = 1;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Kindacode.com'),
),
child: SafeArea(
child: Container(
padding: const EdgeInsets.all(15),
width: double.infinity,
child: Column(children: [
CupertinoSlider(
value: _currentValue,
min: 0,
max: 10,
divisions: 10,
onChanged: (selectedValue) {
setState(() {
_currentValue = selectedValue;
});
}),
SizedBox(height: 25),
Text('Current value: ${_currentValue.toString()}')
]),
),
),
);
}
}
Conclusion
AdvertisementsWeÂ’ve gone over a simple example of using the CupertinoSlider widget to make an iOS-style slider in Flutter. If youÂ’d like to learn more about iOS-style, widgets, take a look at the following articles:
- How to use Cupertino icons in Flutter
- Flutter CupertinoSegmentedControl Example
- Example of CupertinoSliverNavigationBar in Flutter
- Flutter: Cupertino ActionSheet Example
- Working with Cupertino Date Picker in Flutter
You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.