Menu
CoddyTech

Getters in Your Classes

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

Some values do not need to be stored, because they follow from others. How many glasses are left is the goal minus the glasses so far. A getter works it out each time you ask:

class WaterLog {
  int glasses = 0;
  int goal = 8;

  int get left => goal - glasses;
  bool get done => glasses >= goal;
}

A getter has a type, the word get and a name, with no parentheses. => means "the result is". You read it like a field: log.left, never log.left().

A field would keep the number from when it was set. A getter is worked out again on every read, so it is never out of date: drink a glass and log.left is one less on the next build.

challenge icon

Challenge

Easy

The page does the math itself, and once the goal is met it counts below zero. Move the rules into WaterLog:

  • Add a getter left: the goal minus the glasses.
  • Add a getter done: true once the glasses reach the goal.
  • Show Goal reached! when log.done, and otherwise 8 to go, 7 to go and so on from log.left.

Try it yourself

import 'package:flutter/material.dart';

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

class WaterLog {
  int glasses = 0;
  int goal = 8;

  void drink() {
    glasses = glasses + 1;
  }
}

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 log = WaterLog();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Water')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '${log.goal - log.glasses} to go',
              style: const TextStyle(fontSize: 32),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  log.drink();
                });
              },
              child: const Text('Drink a glass'),
            ),
          ],
        ),
      ),
    );
  }
}
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