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 truea || 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 trueThe 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
EasyThe door opens only with the key and the code. Change the two lines:
- the first says
The door is openwhen you have the key and know the code, otherwiseThe door is locked - the second says
Getting closerwhen you have the key or know the code, otherwiseFind 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'),
),
],
),
),
);
}
}
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