Menu
CoddyTech

And, Or and Not in Dart

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

Often one bool is not enough. Dart joins them with three operators:

  • a && b (and): true only when both are true
  • a || b (or): true when at least one is true
  • !a (not): flips true and false
bool _hasTicket = true;
bool _isLate = false;

_hasTicket && !_isLate   // true: you can board
_hasTicket || _isLate    // true: at least one is true

The result is a bool, so it fits before the ? of a conditional, or in an if. Parentheses make it easier to read:

Text((_hasTicket && !_isLate) ? 'Board now' : 'Wait')
challenge icon

Challenge

Easy

The door opens only with the key and the code. Change the two lines:

  • the first says The door is open when you have the key and know the code, otherwise The door is locked
  • the second says Getting closer when you have the key or know the code, otherwise Find the key and the code

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> {
  bool _hasKey = false;
  bool _knowsCode = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Door')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('The door is locked', style: TextStyle(fontSize: 24)),
            const Text('Find the key and the code'),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _hasKey = true;
                });
              },
              child: const Text('Take the key'),
            ),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _knowsCode = true;
                });
              },
              child: const Text('Learn the code'),
            ),
          ],
        ),
      ),
    );
  }
}
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