Flutter 包含底部tabs的 基础页面

25 min read
import 'package:flutter/material.dart';

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

class Page1 extends StatelessWidget {
  const Page1({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Text('Page1');
  }
}

class Page2 extends StatelessWidget {
  const Page2({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Text("Page2");
  }
}

class Page3 extends StatelessWidget {
  const Page3({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Text("Page3");
  }
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _index = 0;
  List<Widget> items = [
    const Page1(),
    const Page2(),
    const Page3(),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(),
        bottomNavigationBar: BottomNavigationBar(
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: '首页',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.business),
              label: '商家',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.school),
              label: '学校',
            ),
          ],
          currentIndex: _index,
          onTap: (index) {
            setState(() {
              _index = index;
            });
          },
        ),
        body: IndexedStack(
          index: _index,
          children: items,
        ),
      ),
    );
  }
}

IndexedStack 是一个管理页面显示层级的容器。

使用 index 属性确定当前容器里那个页面在最顶上,容器里的页面通过 children 属性设置,要求是一个 Widget 数组。

当 BottomNavigationBar 中的图标被点击后,对应点击事件会回调 onTap属性指定的方法,将当前的点击索引值传递回调函数,因此可以利用这个方式控制 IndexedStack 的页面层级切换。

使用了状态变量_index 存储IndexedStatck当前显示页面的索引值,然后当 BottomNavigationBar的图标点击事件发生后,在回调函数中使用 setState 更新状态变量_index` 来刷新当前界面。