Flutter CupertinoSlider Example

Last updated on July 15, 2021 The Frog Loading... Post a comment

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.

A Prefatory Note

The CupertinoSlider class requires 2 parameters:

  • 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

We’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:

You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles