首页 > 建站教程 > APP开发,混合APP >  通过PreferredSizeWidget实现自定义Appbar正文

通过PreferredSizeWidget实现自定义Appbar

AppBar是Scaffold组件的一个属性,通常是一个标题,至多再在左侧加个按钮,右侧再加几个按钮,如果想实现页面的AppBar是个tab栏,可以左右切换,而并非一个简单粗暴的标题,就可以使用自定义AppBar,AppBar组件是PreferredSizeWidget的实现,下面的代码即可实现自定义appBar:
import 'package:flutter/material.dart';

class ListTitleBar extends StatefulWidget implements PreferredSizeWidget {

  final String _left;
  final String _right;

  ListTitleBar(this._left, this._right);

  @override
  State<StatefulWidget> createState() => new ListTitleBarState(_left, _right);

  // PreferredSizeWidget必须要重写 preferredSize,即AppBar高度
  @override
  Size get preferredSize {
    return new Size.fromHeight(20.0);
  }

}

class ListTitleBarState extends State<ListTitleBar> {

  String _leftTitle;
  String _rightTitle;

  ListTitleBarState(this._leftTitle, this._rightTitle);

  @override
  Widget build(BuildContext context) {

    return new Container(

      decoration: new BoxDecoration(
        color: Colors.redAccent,
        border: new Border.all(color: Colors.black),
      ),

      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[

          // 左tab标题
          new Column(
            children: <Widget>[
              new Container(
                color: Colors.redAccent,
                padding: const EdgeInsets.all(10.0),
                child: new Text(_leftTitle,
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize: 18.0
                  ),
                ),
              )
            ],
          ),

          // 右tab标题
          new Column(
            children: <Widget>[
              new Container(
                color: Colors.redAccent,
                padding: const EdgeInsets.all(10.0),
                child: new Text(_rightTitle,
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize: 18.0
                  ),
                ),
              )
            ],
          ),

        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
     super.dispose();
  }

}