【问题标题】:Flutter how to add indent and end indent to app bar?Flutter如何在应用栏添加缩进和结束缩进?
【发布时间】:2021-08-09 17:38:53
【问题描述】:

Please check this screenshot

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

【问题讨论】:

  • 你的AppBar 从来没有自己的背景颜色吗?
  • 这有什么关系?我为此所做的设计有一个与身体其余部分齐平的 AppBar。没有海拔也没有颜色。
  • 因为,有一种hacky方法可以为您的AppBar添加边距,但是margin意味着您的应用背景颜色将出现在应用栏的左右两侧。除了这种方法和创建自己的 appbar 之外,我在源代码中检查的内容似乎是不可能的。它渲染 Row([leading, text, trailing]) 并且不能给 Row 填充,所以你只能设置单独的填充,这就是我问的原因。
  • 我可以将AppBar 设置为透明或白色,因此颜色是否显示无关紧要。我找不到将填充或边距添加到 AppBar 的方法,您能帮我解决这个问题吗?
  • 添加了一个答案,看看吧。你实际上也可以拥有任何你想要的背景颜色。检查它是否适合您。

标签: flutter user-interface dart


【解决方案1】:

现在,要回答是否建议使用这种方法是一个棘手的问题,但您基本上可以通过对原始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,在实际AppBar 的每一侧都有一个SizedBox

但是由于这只是一个Widget,并没有扩展AppBar,所以我们不能直接在Scaffold.appBar中使用它。

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

来自AppBar的文档,

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

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

然后,你基本上可以在Scaffold中使用你的新小部件了

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

输出。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2014-04-28
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多