Menu
CoddyTech

And, Or и Not в Dart

Часть раздела Добавляем интерактивность путешествия по Flutter на Coddy. Урок 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: хотя бы одно условие истинно

Результат имеет тип 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