Flutter 中 AppBar

156 阅读1分钟

在Flutter中,AppBar是一个常用的顶部导航栏控件,通常用于在应用程序的顶部显示标题、操作按钮等内容。AppBar可以与Scaffold一起使用,以便自动与屏幕顶部的系统状态栏融合,并且可以包含各种操作按钮、标题等内容。

以下是一个简单的示例代码,演示如何在Flutter应用中使用AppBar

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          // 设置标题
          title: Text('AppBar Example'),
          // 设置背景色
          backgroundColor: Colors.blue,
          // 设置标题居中
          centerTitle: true,
          // 设置操作按钮
          actions: [
            IconButton(
              icon: Icon(Icons.search),
              onPressed: () {
                // 处理搜索按钮点击事件
              },
            ),
            IconButton(
              icon: Icon(Icons.more_vert),
              onPressed: () {
                // 处理更多按钮点击事件
              },
            ),
          ],
        ),
        body: Center(
          child: Text('This is the body of the page'),
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,包含一个带有标题和操作按钮的AppBar。标题被设置为“AppBar Example”,背景色为蓝色,标题居中显示。操作按钮包括一个搜索按钮和一个更多按钮。

除了示例中提到的属性之外,AppBar还有许多其他属性,例如elevation用于设置阴影效果的高度,brightness用于设置状态栏图标和文字的颜色主题等。AppBar非常灵活,可以根据应用程序的需要进行定制。