Flutter如何自定义AppBar导航栏

在Flutter中如何自定义AppBar导航栏的样式?比如我想修改背景颜色、添加自定义图标按钮,或者调整标题的位置和样式,应该怎么实现?有没有比较完整的代码示例可以参考?

2 回复

Flutter中自定义AppBar可通过AppBar组件的属性实现,如修改backgroundColortitleleadingactions等。也可使用PreferredSizeSliverAppBar实现更复杂的自定义布局。

更多关于Flutter如何自定义AppBar导航栏的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,可以通过以下几种方式自定义AppBar导航栏:

1. 使用AppBar组件的属性

AppBar(
  title: Text('自定义标题'),
  leading: IconButton(
    icon: Icon(Icons.menu),
    onPressed: () {
      // 菜单按钮点击事件
    },
  ),
  actions: [
    IconButton(
      icon: Icon(Icons.search),
      onPressed: () {
        // 搜索按钮点击事件
      },
    ),
    IconButton(
      icon: Icon(Icons.more_vert),
      onPressed: () {
        // 更多按钮点击事件
      },
    ),
  ],
  backgroundColor: Colors.blue,
  elevation: 4.0,
  centerTitle: true,
)

2. 完全自定义导航栏

使用PreferredSizeWidget创建完全自定义的导航栏:

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  @override
  Size get preferredSize => Size.fromHeight(60.0);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      color: Colors.blue,
      child: Row(
        children: [
          IconButton(
            icon: Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () => Navigator.pop(context),
          ),
          Expanded(
            child: Text(
              '自定义导航栏',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          IconButton(
            icon: Icon(Icons.settings, color: Colors.white),
            onPressed: () {},
          ),
        ],
      ),
    );
  }
}

// 使用方式
Scaffold(
  appBar: CustomAppBar(),
  body: Container(),
)

3. 使用SliverAppBar实现可伸缩效果

CustomScrollView(
  slivers: [
    SliverAppBar(
      expandedHeight: 200.0,
      floating: false,
      pinned: true,
      flexibleSpace: FlexibleSpaceBar(
        title: Text('可伸缩导航栏'),
        background: Image.network(
          '图片URL',
          fit: BoxFit.cover,
        ),
      ),
    ),
    // 其他Sliver组件
  ],
)

主要自定义属性说明:

  • title: 标题内容
  • leading: 左侧组件(通常是返回按钮)
  • actions: 右侧操作按钮列表
  • backgroundColor: 背景颜色
  • elevation: 阴影高度
  • flexibleSpace: 可伸缩区域(用于SliverAppBar)
  • bottom: 底部组件(如TabBar)

选择哪种方式取决于你的具体需求:简单的样式调整使用AppBar属性,完全自定义布局使用PreferredSizeWidget,需要可伸缩效果则使用SliverAppBar。

回到顶部