Flutter: 自定义AppBar

Flutter: 自定义AppBar

这是一个可以指定SafeArea区域背景色的AppBar
先上代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class XAppBar extends StatefulWidget implements PreferredSizeWidget {
  final Widget child; //从外部指定内容
  final Color statusBarColor; //设置statusbar的颜色
  final double height;

  XAppBar(
      {required this.child,
      required this.height,
      required this.statusBarColor,
      Key? key})
      : super(key: key);

  @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,
      ),
    );
  }
  
}

原谅我比较懒,自定义AppBar也比较简单
写代码的时候顺手加上注释就发出来了
特意写了很多注释,相信大家配合注释看没有问题

再上一张效果图

posted @ 2019-06-06 16:34  痴人指路  阅读(6822)  评论(0编辑  收藏  举报