【发布时间】:2018-04-23 14:47:34
【问题描述】:
如何在 Flutter 中将 AppBar 标题替换为图片徽标?
【问题讨论】:
如何在 Flutter 中将 AppBar 标题替换为图片徽标?
【问题讨论】:
title 属性采用 Widget,因此您可以将任何小部件传递给它。
例如,添加到资产中的图像
Scaffold(
appBar: AppBar(
title: Image.asset('assets/title.png', fit: BoxFit.cover),
),
body: ...
)
【讨论】:
final Image titleImage = Image.asset(...) 如果图像不是最终图像,它将导致比简单的Text 小部件更多的重建。
Image final 会跳过一些重建。非常感谢!
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
'assets/logo.png',
fit: BoxFit.contain,
height: 32,
),
Container(
padding: const EdgeInsets.all(8.0), child: Text('YourAppTitle'))
],
),
)
【讨论】:
应用主题可能是最好的长期方案。 (确保您已将徽标图像正确添加到资产文件夹并更新了“pubspec.yaml”文件)。
在您的“样式”文件中创建图像widget,例如(高度、重量、路径、对齐方式由您决定):
Image appLogo = new Image(
image: new ExactAssetImage("assets/images/AppLogo.png"),
height: 28.0,
width: 20.0,
alignment: FractionalOffset.center);
在 AppBar 的 title 字段中,添加“appLogo”(或任何您
命名为widget),像这样(不要忘记导入你的'style'文件):
child: Scaffold(
appBar: AppBar(
title: appLogo,
),
现在,如果您需要更改此徽标,您只需使用新的图像路径编辑您的 style.dart 文件即可。如果您有不同的主题并在每个样式文件中以相同的方式命名小部件,您还可以通过导入相应的样式快速实现不同的样式(例如“style1”、“style2”等)文件只放在几个地方。
【讨论】:
问题是 AppBar 不适合它的高度与图像大小。为了解决这个问题,我设置了图像和 AppBar 高度(包括填充)
这是我的代码:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Image.asset(
"assets/images/logo_light.png",
fit: BoxFit.contain,
height: 72,
),
toolbarHeight: 88,
actions: [
IconButton(onPressed: () => {}, icon: Icon(Icons.search)),
],
),
);
【讨论】:
以上对我来说不太适用,这会将我想要的图片背景添加到整个应用栏,并留下保留标题的选项。针对颤振/飞镖 2.0 空安全性进行了更新
Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
title: Text('App Bar!'),
flexibleSpace: Image(
image: AssetImage('images/bar1.jpg'),
fit: BoxFit.cover,
),
backgroundColor: Colors.transparent,
),
body: Container()
)
【讨论】:
AppBar(
centerTitle: true,
title: Image.asset('assets/your_logo.png', height: 32),
backgroundColor: Theme.of(context).primaryColor,
)
【讨论】: