微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter: 自定义AppBar

Flutter: 自定义AppBar

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


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

/**
 * 这是一个可以指定SafeArea区域背景色的AppBar
 * PreferredSizeWidget提供指定高度的方法
 * 如果没有约束其高度,则会使用PreferredSizeWidget指定的高度
 */
class XFileAppbar extends StatefulWidget implements PreferredSizeWidget {

  final double contentHeight; //从外部指定高度
  final Widget contentChild;  //从外部指定内容
  final Color statusBarColor; //设置statusbar的颜色

  XFileAppbar({this.contentChild, this.contentHeight, this.statusBarColor}): super();

  @override
  State<StatefulWidget> createState() {
    return new _XFileAppbarState();
  }

  @override
  Size get preferredSize => new Size.fromHeight(contentHeight);
  
}


/**
 * 这里没有直接用SafeArea,而是用Container包装了一层
 * 因为直接用SafeArea,会把顶部的statusBar区域留出空白
 * 外层Container会填充SafeArea,指定外层Container背景色也会覆盖原来SafeArea的颜色
 */
class _XFileAppbarState extends State<XFileAppbar> {
  @override
  Widget build(BuildContext context) {
    return new Container(
        color: widget.statusBarColor,
        child: new SafeArea(
        top: true,
        child: widget.contentChild,
      ),
    );
  }
  
}

使用方法

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'),    //注意:加入了child,AppBar的高度会是Container的实际高度,而不是你指定的高度
      color: Colors.blue,
    );
    return Scaffold(
      appBar: new XFileAppbar(
        contentChild: topBar,
        contentHeight: 100.0,
        statusBarColor: bkgColor,
      ),
    );
  }
  
}

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

再上一张效果

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐