下面是我用 Stack 和 PreferredSize 来创建它的方式。这样做可以让我们重复使用默认的 AppBar 属性,例如当在 body 中有 ListView 时使 AppBar 粘在屏幕顶部。
_appBar(height) => PreferredSize(
preferredSize: Size(MediaQuery.of(context).size.width, height+80 ),
child: Stack(
children: <Widget>[
Container(
child: Center(
child: Text("Home", style: TextStyle(fontSize: 25.0,
fontWeight: FontWeight.w600,
color: Colors.white),),),
color:Theme.of(context).primaryColor,
height: height+75,
width: MediaQuery.of(context).size.width,
),
Container(),
Positioned(
top: 100.0,
left: 20.0,
right: 20.0,
child: AppBar(
backgroundColor: Colors.white,
leading: Icon(Icons.menu, color: Theme.of(context).primaryColor,),
primary: false,
title: TextField(
decoration: InputDecoration(
hintText: "Search",
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey))),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search, color: Theme.of(context).primaryColor), onPressed: () {},),
IconButton(icon: Icon(Icons.notifications, color: Theme.of(context).primaryColor),
onPressed: () {},)
],
),
)
],
),
);
在脚手架内,我们只需调用上面的 appbar。我们想要传递 AppBar().preferredSize.height 作为默认的 appBar 高度在不同设备(例如:iPhone 8 Plus 和 iPhone 11 Pro Max)上是不同的。
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: _appBar(AppBar().preferredSize.height),
body: ListView(),
);
})