首页 > 解决方案 > Flutter如何在应用栏添加缩进和结束缩进?

问题描述

请检查此屏幕截图

我知道 AppBar 中的 titleSpacing ,但这只会应用于标题,如果我放置任何前导图标,那将不会像预期的那样对我有用。我的整个屏幕左右都有一个 28 像素的填充,我可以使用 Scaffold 主体中的 Padding 小部件来完成。但我正在努力在 appBar 中做同样的事情。我不想为每个图标或标题添加填充,因为我有多个操作图标。我只想在 appBar 的第一个元素的左侧添加一个特定的填充,并且为 appBar 的最后一个操作图标添加相同的填充。

标签: flutteruser-interfacedart

解决方案


现在,要回答是否建议使用这种方法是一个棘手的问题,但是您基本上可以通过对原始AppBar.

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final AppBar appBar;

  CustomAppBar(this.appBar);

  @override
  Size get preferredSize => Size.fromHeight(56);

  @override
  Widget build(BuildContext context) => Row(children: [
      SizedBox(width: 16),
      Expanded(child: appBar),
      SizedBox(width: 16),
    ]);
}

class CAE extends StatelessWidget {
  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: CustomAppBar(AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
      title: Text(
        'Custom App Bar',
        style: TextStyle(color: Colors.black),
      ),
      leading: IconButton(icon: Icon(Icons.calendar_today)),
      actions: [
        IconButton(icon: Icon(Icons.calendar_today)),
        IconButton(icon: Icon(Icons.calendar_today))
      ],
    )),
    body: Container(
      color: Colors.deepOrange,
    ),
  );
}

我们基本上是在创建一个在实际的每一侧Row都有一个。SizedBoxAppBar

但是由于这只是 aWidget并且没有 extends AppBar,我们不能Scaffold.appBar直接使用它。

你看,AppBar只是一个Widget实现PreferredSizeWidget. 所以我们让我们的自定义小部件实现相同的类。为此,我们需要覆盖preferredSizegetter。

从文档中AppBar

preferredSize = Size.fromHeight(toolbarHeight ?? 56 + (bottom?.preferredSize.height ?? 0.0)),

可以简化为just Size.fromHeight(56),这就是我在覆盖中使用的。

然后,您基本上可以Scaffold像这样使用新的小部件

Scaffold(appBar: CustomAppBar(AppBar(/* Whatever your actual AppBar is */)))

输出。

在此处输入图像描述

如果您确实想设置背景颜色,请先换行,然后使用 aContainer而不是,SizedBox然后设置color为它。


推荐阅读