代码片段

Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          child: Column(
            children: [
              _notice(),
              _tabBar(),
            ],
          ),
          preferredSize: Size.fromHeight(kToolbarHeight + 20)),// +20是加上_notice的高度
      body: TabBarView(
        children: _tabViews,
        controller: _tabController,
      ),
    );
    // TabBar(tabs: _tabs,controller: _tabController,)
  }

完整代码

import 'package:flutter/material.dart';
import 'package:flutter_app/utils/util.dart';
import 'package:marquee/marquee.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late TabController _tabController;
  List<Tab> _tabs = [Tab(text: '推荐'), Tab(text: '精选')];
  List<Widget> _tabViews = [Text('推荐'), Text('精选')];

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

    // 初始化tab控制器
    _tabController =
        new TabController(initialIndex: 1, length: _tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
          child: Column(
            children: [
              _notice(),
              _tabBar(),
            ],
          ),
          preferredSize: Size.fromHeight(kToolbarHeight + 20)),// +20是加上_notice的高度
      body: TabBarView(
        children: _tabViews,
        controller: _tabController,
      ),
    );
    // TabBar(tabs: _tabs,controller: _tabController,)
  }

  Widget _notice() {
    return Visibility(
      child: Expanded(
        child: Container(
          color: HexColor('#fdf6ec'),
          child: InkWell(
            onTap: (){print('_notice click');},
            child: Marquee(
              text: '这是一条公告内容xxxxxx,点击前往',
              style: TextStyle(color: HexColor('#fbc473')),
              blankSpace:30,
            ),
          ),
        )
      ),
      visible: true,
    );
  }

  TabBar _tabBar(){
    return TabBar(
        tabs: _tabs,
        controller: _tabController,
      );
  }
}

GeorgieのBlog,分享生活的点点滴滴,分享代码干货