Menu
CoddyTech

Grey Out a Button

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

In Your First Button, onPressed: null greyed a button out. Now you can decide while the app runs: give onPressed the function when the button makes sense, and null when it does not.

ElevatedButton(
  onPressed: _count > 0 ? _decrease : null,
  child: const Text('Minus'),
)

The ? : picks between the method and null. Each time setState builds the screen again, the comparison runs again, so the button turns grey and back on its own.

A greyed out button tells people why nothing would happen, before they tap. A button that is pressable but quietly does nothing just looks broken.

challenge icon

Challenge

Easy

The cart can go below zero items. Grey out the Remove button when there are no items, so it can only be pressed while _items is more than 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> {
  int _items = 0;

  void _add() {
    setState(() {
      _items++;
    });
  }

  void _remove() {
    setState(() {
      _items--;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Cart')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('Items: $_items', style: const TextStyle(fontSize: 24)),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: _add, child: const Text('Add')),
            ElevatedButton(onPressed: _remove, child: const Text('Remove')),
          ],
        ),
      ),
    );
  }
}
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