DartのAND・OR・NOT
CoddyのFlutterジャーニー「アプリをインタラクティブにする」セクションの一部。レッスン 19/34。
bool が 1 つだけでは不十分なことがよくあります。Dart では 3 つの演算子を組み合わせます。
a && b(かつ):両方が真の場合にのみ真a || b(または):少なくとも一方が真の場合に真!a(否定):真と偽を反転
bool _hasTicket = true;
bool _isLate = false;
_hasTicket && !_isLate // true: 乗車できます
_hasTicket || _isLate // true: 少なくとも一方がtrueです結果は bool なので、条件式の ? の前や、if の中で使えます。括弧を使うと読みやすくなります。
Text((_hasTicket && !_isLate) ? 'Board now' : 'Wait')チャレンジ
簡単ドアは鍵とコードがそろったときだけ開きます。次の2行を変更してください。
- 1行目は、鍵を持っていて、かつコードを知っている場合は
The door is openと表示し、それ以外の場合はThe door is lockedと表示します。 - 2行目は、鍵を持っているか、またはコードを知っている場合は
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'),
),
],
),
),
);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
アプリをインタラクティブにするのすべてのレッスン
自分で練習してみよう: Flutterオンラインコンパイラ