Flutter

Flutter 自定义一个AppBar

2020-07-07  本文已影响0人  代瑶

自定义AppBar 先上图, 看效果.


image.png

这个其实很简单, 我们可以利用appbar 的title, 它后面需要实例化一个Widget嘛, 所以这样写

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 1,
        title: HomeAppBar() //注意这行, HomeAppBar 是我们自己写的
      ),
      body: Container(),
    );
  }

下面贴HomeAppBar代码

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

class HomeAppBar extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //横向布局
    return Row(
      children: <Widget>[
        //因为它是左右占比结构,所以使用Expanded 的flex
        Expanded(
          flex: 1,
          child: InkWell(
              //利用InkWell组件包裹其他组件,则拥有了点击事件
              onTap: () {
                print('点击了');
              },
              child: Container(
                //所有组件垂直居中
                alignment: Alignment.center,
                height: 40,
                padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                //带有弧度的边框,有背景色
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.black12,
                ),
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Row(
                      //常用于Row和Column控件
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.search, color: Colors.black38),
                        SizedBox(width: 10), //常用于两个组件之间的分隔
                        Text(
                          '高考加油',
                          style: TextStyle(color: Colors.black38),
                        )
                      ],
                    ),
                    Align(
                      alignment: Alignment.centerRight,
                      child: IconButton(
                        icon: Icon(Icons.picture_in_picture),
                        color: Colors.black38,
                        onPressed: () {
                          print('点击右边图标');
                        },
                      ),
                    )
                  ],
                ),
              )),
        ),
        Expanded(
          flex: 0,
          child: IconButton(
            icon: Icon(Icons.notifications),
            color: Colors.black38,
            onPressed: () {},
          ),
        ),
      ],
    );
  }
}

上一篇 下一篇

猜你喜欢

热点阅读