Flutter 自定义appbar(转载)

148 阅读1分钟
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高度
      width: 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,
      ),
    );
  }
}

效果图

image.png 转载