Menu
CoddyTech

Pick a Value With a Slider

Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 29 of 34.

A Slider picks a number from a range by dragging. Like a switch, it draws its value: and calls onChanged with the new one:

Slider(
  value: _size,
  min: 0,
  max: 50,
  divisions: 5,
  onChanged: (double value) {
    setState(() {
      _size = value;
    });
  },
)

min: and max: are the two ends. divisions: makes it jump in steps: 5 divisions from 0 to 50 means 0, 10, 20, 30, 40 and 50. Without it, every value in between is possible. You can also tap the track, and the slider jumps there.

The value is always a double, so it shows as 20.0. _size.round() rounds it to the nearest whole number, an int, which shows as 20.

challenge icon

Challenge

Easy
  • Make the slider move: store its value in _volume with setState.
  • Show the volume as a whole number under it: Volume: 20, not Volume: 20.0.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double _volume = 20;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Sound')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.volume_up, size: 64),
            Slider(
              value: _volume,
              min: 0,
              max: 100,
              divisions: 10,
              onChanged: (double value) {},
            ),
            Text('Volume: ?', style: const TextStyle(fontSize: 24)),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Making It Interactive

Practice on your own: Online Flutter compiler