Menu
CoddyTech

显示和隐藏组件

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

如果只想在某些时候显示一个组件,可以在组件前面直接加上 if,放在 children 列表中:

Column(
  children: [
    const Text('Question'),
    if (_showHint) const Text('A hint'),
  ],
)

当 _showHint 为 false 时,提示并不是被隐藏了,而是根本不在列表中,后面的组件会向上移动来填补空位。当它为 true 时,提示就会显示出来。这个 if 没有花括号,也没有 else:它是列表中的 if 写法,就像你之前用来创建组件列表的 for 一样。

显示和隐藏内容的按钮通常会用 ! 切换一个布尔值,并用 ? : 更改自身的标签。

challenge icon

挑战

简单

答案 Paris 始终显示在屏幕上。只有当 _showAnswer 为 true 时才显示它。按钮已经会切换 _showAnswer 的值;答案隐藏时,让按钮标签显示 Show answer,答案显示时则显示 Hide answer。

亲手试试

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 _showAnswer = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Quiz')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('What is the capital of France?', style: TextStyle(fontSize: 20)),
            const Text('Paris', style: TextStyle(fontSize: 32)),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _showAnswer = !_showAnswer;
                });
              },
              child: const Text('Show answer'),
            ),
          ],
        ),
      ),
    );
  }
}
quiz icon自我测试

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

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

自己练习: Flutter 在线编译器