Flutter: 自定義AppBar


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高度
      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也比較簡單
寫代碼的時候順手加上注釋就發出來了
特意寫了很多注釋,相信大家配合注釋看沒有問題

再上一張效果圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM