How to use Flutter Slider: Happiness Calculator App – Step 1

We are going to build a Flutter App. Name is “Happiness Calculator”. In this section, we will learn how to use Slider Widget.

So far we have been progressing step-by-step.

We have learned how to use enum. After that, we have used ternary operator to reduce the code length.

In this section we will learn what is the Slider widget. How to use it. Moreover, why we need the Slider Widget.

What is Slider Widget

Firstly, the Slider Widget requires a Material widget as its ancestor.

Secondly, it inherits from a MediaQuery widget. That means we need the MaterialApp widget at the top of the Widget tree.

Next, we need to remember another important thing.

The Slider Widget selects a range of values. It starts from the minimum and might proceed to the maximum.

As a result, the state changes. The build() method rebuilds the Widget. Therefore, we also need a Stateful Widget that will track the number.

Why?

Because as we drag the slider, the number changes.

Let us take a look. That will give us an idea how the Slider Widget works.


Slider displays with the minimum value
Slider displays the minimum value

As we drag the Slider, it proceeds to the maximum value.

During dragging the state changes. However, the Slider widget does not maintain any state.

On the contrary, to maintain state, the slider widget calls the onChanged callback.

As a result, when we drag it further, the number increases.


Slider proceeds to the maximum value
Slider proceeds to the maximum value

Why we need and how to use Slider

Firstly, with the help of the Slider Widget we can change a value. This mechanism might help us to decide something else with respect to that value.

Since we want to calculate happiness, we can set the value by dragging the slider.

Secondly, the onChanged property expects a callback that must have the setState() method.

Not only that, it also passes a double value that takes the new value as the value changes.

Finally we see how the Slider Widget uses the abstraction.

To make it happen, we just initialise an integer value which points to the minimum value. Once the range is set, we can provide the maximum value also.

Slider(
                      value: height.toDouble(),
                      min: 120.0,
                      max: 220.0,
                      activeColor: activeColor,
                      inactiveColor: Colors.black26,
                      onChanged: (double newValue) {
                        setState(() {
                          height = newValue.round();
                        });
                      },
                    ),

We see in the above code many properties of the Slider Widget. But we can customise it more by adding more features to it.

Let us take a look at the full code, so it will clear every confusion.

import 'package:flutter/material.dart';

import '../model/constants.dart';
import '../model/container_color.dart';

class HappinessHomePage extends StatefulWidget {
  const HappinessHomePage({
    Key? key,
    required this.title,
  }) : super(key: key);

  final String title;

  @override
  State<HappinessHomePage> createState() => _HappinessHomePageState();
}

class _HappinessHomePageState extends State<HappinessHomePage> {
  ContainerColor? selectedContainer;
  int height = 120;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              children: [
                expandEnum(ContainerColor.first),
                expandEnum(ContainerColor.second),
              ],
            ),
            Expanded(
              child: Container(
                margin: const EdgeInsets.all(15.0),
                alignment: Alignment.center,
                color: inactiveColor,
                width: double.infinity,
                child: Column(
                  children: [
                    const Text('How The Slider Widget Works'),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: [
                        Text(
                          height.toString(),
                          style: const TextStyle(
                            fontSize: 60.0,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                        const Text(
                          'cm',
                          style: TextStyle(
                            fontSize: 15.0,
                            fontWeight: FontWeight.w100,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      ],
                    ),
                    Slider(
                      value: height.toDouble(),
                      min: 120.0,
                      max: 220.0,
                      activeColor: activeColor,
                      inactiveColor: Colors.black26,
                      onChanged: (double newValue) {
                        setState(() {
                          height = newValue.round();
                        });
                      },
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Expanded expandEnum(ContainerColor? containerColor) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(18.0),
        child: GestureDetector(
          onTap: () {
            setState(() {
              selectedContainer = containerColor;
            });
          },
          child: Container(
            alignment: Alignment.center,
            color: selectedContainer == containerColor
                ? activeColor
                : inactiveColor,
            width: 150.0,
            height: 150.0,
            child: const Text('Press Me'),
          ),
        ),
      ),
    );
  }
}

In the next section we will learn to customise the Slider. For example the round thumb inside the Slider might be bigger.

Previously we have learned how to use a common theme across the entire Flutter App.

We can implement that concept here. By the way, if you want to clone this part of the project please visit the respective branch of GitHub repository.

So stay tuned.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

2 responses to “How to use Flutter Slider: Happiness Calculator App – Step 1”

  1. […] Firstly, we have discussed enum before. Secondly, we have reduced the code size by using the ternary operator. And finally, we have discussed Slider in Flutter. […]

  2. […] Happiness Calculator App works on simple principle. Between the three factors, when greed is too high, and other two […]

Leave a Reply