Menu
CoddyTech

带导航栏的标签页

本课属于 Coddy Flutter 学习旅程的“列表和屏幕”单元。第 23 课,共 33 课。

许多应用会将主要页面放在屏幕底部的标签页中。NavigationBar负责绘制这些标签页,你需要将它传给 Scaffold 的 bottomNavigationBar:。

NavigationBar(
  selectedIndex: index,
  onDestinationSelected: (int i) {
    setState(() {
      index = i;
    });
  },
  destinations: const [
    NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
    NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
  ],
)

每个 NavigationDestination 都是一个标签页,包含一个图标和一个标签。selectedIndex表示当前高亮的标签页,从 0 开始计数。点击标签页时,onDestinationSelected会收到它的索引。

导航栏本身不会记住当前标签页:你需要在状态中保存 index,并通过 setState 更改它。主体区域会显示与该索引对应的页面,这里是组件列表中的 pages[index]。

challenge icon

挑战

简单

导航栏有三个标签页,但点击它们没有任何效果。添加 onDestinationSelected:,让点击的标签页高亮显示,并显示对应页面:Favorites 对应 Favorites page,Settings 对应 Settings page。

亲手试试

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int index = 0;
  final List<Widget> pages = const [
    Center(child: Text('Home page')),
    Center(child: Text('Favorites page')),
    Center(child: Text('Settings page')),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('My App')),
      body: pages[index],
      bottomNavigationBar: NavigationBar(
        selectedIndex: index,
        destinations: const [
          NavigationDestination(icon: Icon(Icons.home), label: 'Home'),
          NavigationDestination(icon: Icon(Icons.favorite), label: 'Favorites'),
          NavigationDestination(icon: Icon(Icons.settings), label: 'Settings'),
        ],
      ),
    );
  }
}
quiz icon自我测试

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

列表和屏幕中的所有课

自己练习: Flutter 在线编译器