Flutter导航栏背景图片
项目需求
在真实的项目开发中,我们会遇到各式各样的导航栏,而flutter系统自带导航栏很难满足我们的需求,因为我们就需要自定义AppBar
注意点
我们自定义的导航栏需要实现PreferredSizeWidget接口,即
class MyAppBar extends StatefulWidget implements PreferredSizeWidget
直接上代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class LYAppBar extends StatefulWidget implements PreferredSizeWidget {
final double barHeight;
final Color backgroundColor;
final String backgroundImageName;
final Widget leadingWidget;
final Widget trailingWidget;
final Widget centerWidget;
final Brightness brightness;
final double elevation;
LYAppBar({Key key,this.barHeight = 88,this.backgroundColor = Colors.white,this.backgroundImageName,this.leadingWidget,this.trailingWidget,@required this.centerWidget,this.brightness,this.elevation = 0}):super(key: key);
@override
_LYAppBarState createState() => _LYAppBarState();
@override
Size get preferredSize => Size.fromHeight(barHeight);
}
class _LYAppBarState extends State {
@override
Widget build(BuildContext context) {
final SystemUiOverlayStyle overlayStyle = widget.brightness == Brightness.dark
? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark;
return AnnotatedRegion(//套AnnotatedRegion是为了增加状态栏控制
value: overlayStyle,
child: Material(//套Material是为了增加elevation
elevation: widget.elevation,
child: Container(
height: widget.barHeight,
decoration: BoxDecoration(
color: widget.backgroundColor,
image: DecorationImage(
image: AssetImage(widget.backgroundImageName),
fit: BoxFit.fill
)
),
child: SafeArea(
child: Stack(
alignment: Alignment.center,
children: [
///左边
Positioned(
left: 0,
child: Container(
padding: EdgeInsets.only(left: 15),
child: widget.leadingWidget,
),
),
///中间
Positioned(
top: 10,
child: Container(
child: widget.centerWidget,
),
),
///右边
Positioned(
right: 0,
child: Container(
padding: EdgeInsets.only(right: 15),
child: widget.trailingWidget,
),
)
]
),
),
),
),
);
}
}
使用
appBar: LYAppBar(
barHeight: 88,
backgroundColor: Colors.blue,
backgroundImageName: 本地图片路径,
centerWidget: Text('分类',style: TextStyle(fontSize: 18,color: Colors.black),),
leadingWidget: Icon(Icons.arrow_back,color: Colors.black,),
trailingWidget: Icon(Icons.arrow_back,color: Colors.black,),
)