Menu
CoddyTech

Keep a Field Private

Part of the State Management section of Coddy's Flutter journey. Lesson 7 of 27.

A thermostat should never go above 26 or below 16 degrees. A warmer method can check that, but only if nobody can change the number another way. While the field is public, any code can write thermostat.degrees = 99.

A name that starts with _ is private: only code in the same file can use it. Put the class in its own file, make the field private, and give the outside a getter to read it and methods to change it:

// thermostat.dart
class Thermostat {
  int _degrees = 20;

  int get degrees => _degrees;

  void warmer() {
    if (_degrees < 26) {
      _degrees = _degrees + 1;
    }
  }
}

The page imports the file with import 'thermostat.dart';. It can read thermostat.degrees, but thermostat.degrees++ no longer compiles: there is a getter and no way to set it. The only way to change the degrees is through the methods, so the limits always hold.

Open thermostat.dart in the file list to edit it.

challenge icon

Challenge

Medium

The buttons change degrees straight from the page, with no limits. In thermostat.dart:

  • Rename the field to _degrees and add a getter degrees that returns it.
  • Add warmer(), which adds 1 up to 26, and cooler(), which takes 1 away down to 16.

Then make the buttons in main.dart call thermostat.warmer() and thermostat.cooler().

Try it yourself

import 'package:flutter/material.dart';

import 'thermostat.dart';

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

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

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

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

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

class _HomePageState extends State<HomePage> {
  final thermostat = Thermostat();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Thermostat')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('${thermostat.degrees}°C', style: const TextStyle(fontSize: 48)),
            const SizedBox(height: 16),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      thermostat.degrees--;
                    });
                  },
                  child: const Text('Cooler'),
                ),
                const SizedBox(width: 16),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      thermostat.degrees++;
                    });
                  },
                  child: const Text('Warmer'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

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

All lessons in State Management

Practice on your own: Online Flutter compiler