Flutter: 自定義AppBar

Flutter: 自定義AppBarapp

這是一個能夠指定SafeArea區域背景色的AppBar
先上代碼:less

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

使用方法:ide

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也比較簡單
寫代碼的時候順手加上註釋就發出來了
特地寫了不少註釋,相信你們配合註釋看沒有問題ui

再上一張效果圖
this

相關文章
相關標籤/搜索