Flutter: 自定义AppBar
这是一个可以指定SafeArea区域背景色的AppBar
先上代码:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/**
* 这是一个可以指定SafeArea区域背景色的AppBar
* PreferredSizeWidget提供指定高度的方法
* 如果没有约束其高度,则会使用PreferredSizeWidget指定的高度
*/
class XAppBar extends StatefulWidget implements PreferredSizeWidget {
final Widget child; //从外部指定内容
final Color statusBarColor; //设置statusbar的颜色
XAppBar({this.child, this.height, this.statusBarColor}) : super();
@override
State<StatefulWidget> createState() {
return new _XAppBarState();
}
@override
Size get preferredSize => new Size.fromHeight(kToolbarHeight);
}
/**
* 这里没有直接用SafeArea,而是用Container包装了一层
* 因为直接用SafeArea,会把顶部的statusBar区域留出空白
* 外层Container会填充SafeArea,指定外层Container背景色也会覆盖原来SafeArea的颜色
*/
class _XAppBarState extends State<XAppBar> {
@override
Widget build(BuildContext context) {
return Container(
height: kToolbarHeight + MediaQuery.of(context).padding.top, //自动设置为系统appbar高度
MediaQuery.of(context).size.width,
color: widget.statusBarColor,
child: SafeArea(
top: true,
bottom: false,
child: widget.child,
),
);
}
}
使用方法:
class XFileView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final Color bkgColor = Color.fromARGB(255, 237, 88, 84);
var topBar = new Container(
// child: new Text('ABC'),
color: Colors.blue,
);
return Scaffold(
appBar: new XAppBar(
child: topBar,
statusBarColor: bkgColor,
),
);
}
}
原谅我比较懒,自定义AppBar也比较简单
写代码的时候顺手加上注释就发出来了
特意写了很多注释,相信大家配合注释看没有问题
再上一张效果图