Menu
CoddyTech

Dart 中的与、或和非

本课属于 Coddy Flutter 学习旅程的“让应用具有交互性”单元。第 19 课,共 34 课。

通常一个 bool 不够。Dart 用三个运算符将它们组合起来:

  • a && b(与):只有两者都为 true 时结果才为 true
  • a || b(或):至少一个为 true 时结果就为 true
  • !a(非):将 true 和 false 互换
bool _hasTicket = true;
bool _isLate = false;

_hasTicket && !_isLate   // true:你可以登机
_hasTicket || _isLate    // true:至少有一个条件为 true

结果是一个 bool,因此可以放在条件表达式的 ? 前面,也可以用于 if。加上括号会更容易阅读:

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

挑战

简单

只有同时有钥匙并知道密码,门才会打开。修改这两行:

  • 当你有钥匙并且知道密码时,第一行显示 The door is open,否则显示 The door is locked
  • 当你有钥匙或者知道密码时,第二行显示 Getting closer,否则显示 Find the key and the code

亲手试试

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 icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

让应用具有交互性中的所有课

自己练习: Flutter 在线编译器