bool 和 ? : 运算符
本课属于 Coddy Flutter 学习旅程的“让应用具有交互性”单元。第 17 课,共 34 课。
有些值只有“是”或“否”两种:灯亮了吗?方框勾选了吗?Dart 用 bool 表示这类值,它有两个值:true 和 false:
bool _isOn = false;在 bool 前面加上 ! 会将它反转,所以 _isOn = !_isOn; 会把 true 变成 false,把 false 变成 true。灯的 _flip 方法已经完成了这个操作。
要根据 bool 显示不同的内容,可以使用条件表达式 ? :。它读起来像个问题:灯亮了吗?亮了就显示这个,否则显示那个。
Text(_isOn ? 'On' : 'Off')
Icon(Icons.star, color: _isOn ? Colors.red : Colors.black)? 前面放一个 true 或 false 值。后面先放 true 时对应的值,然后是 : 和 false 时对应的值。它可以用在任何需要值的地方:文本、颜色、大小。
挑战
简单“Switch”按钮会切换_isOn,但灯看起来始终是关着的。使用? :,这样当_isOn为 true 时,文本显示The light is on,灯泡颜色为Colors.amber;否则,文本显示The light is off,灯泡颜色为Colors.grey。
亲手试试
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 _isOn = false;
void _flip() {
setState(() {
_isOn = !_isOn;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Lamp')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.lightbulb, size: 96, color: Colors.grey),
const Text('The light is off'),
const SizedBox(height: 16),
ElevatedButton(onPressed: _flip, child: const Text('Switch')),
],
),
),
);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
让应用具有交互性中的所有课
自己练习: Flutter 在线编译器