flutter 上滑悬浮吸顶

本文介绍了如何在Flutter中使用RefreshIndicator、NestedScrollView、TabBar和SmartRefresher组件来创建带有下拉刷新和上拉加载功能的TabBar应用,同时实现了TabBar的吸顶效果。示例代码详细展示了轮播图、商品列表和商品分类Tab的实现,以及如何处理数据请求和页面滚动交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 :RefreshIndicator+NestedScrollView+(TabBar、TabView)+SmartRefresher打造可下拉刷新和上拉加载的tab吸顶效果。

上拉吸顶

1.导入

pull_to_refresh: ^2.0.0
flutter_swiper: ^1.1.6

2.RefreshIndicator+NestedScrollView

class ListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage>
    with AutomaticKeepAliveClientMixin ,TickerProviderStateMixin{

  /// 轮播图
  List<BannerModel> bannerList = [];

  SwiperController _swiperController;

  List<GoodsListModel> goodsList = [];

  int pageNum = 1;

  int _position  = 0;

  List<GoodsCategoryBean> _goodsCategoryList = [];
  TabController _tabController;
  bool _isFirstIn = true;

  @override
  void initState() {
    super.initState();
    _swiperController = SwiperController();
    _swiperController.startAutoplay();
    if(_isFirstIn){
      _isFirstIn = false;
    }
    getData();
  }

  @override
  void dispose() {
    _swiperController.stopAutoplay();
    _swiperController.dispose();
    _tabController.dispose();

    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(Icons.arrow_back_ios),
        ),
        iconTheme: IconThemeData(color: Color(0xff999999)),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(),
            Container(
              margin: EdgeInsets.only(right: setWidth(34)),
              child: Text(
                S.current.remenshangpin,
                style: TextStyle(color: Colors.black),
              ),
            ),
            GestureDetector(
              onTap: () {
                esLoadingToast('去搜索');
              },
              child: Image.asset(
                PathConfig.imageSearch,
                fit: BoxFit.cover,
                width: 40.w,
                height: 40.w,
                color: HexColor('#999999'),
              ),
            )
          ],
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        notificationPredicate: (notifation) {
          // 返回true即可,避免下拉刷新时和NestedScrollView滑动冲突
          return true;
        },
        child:NestedScrollView(
          headerSliverBuilder: (BuildContext context,bool b){
            return [initSliverPersistentHeader(),initSliverPersistentHeaderTwo()];
          },
          body: _goodsListView(),
        ), onRefresh: (){
        pageNum = 1;
        getData();
        return Future.value(true);
      },
      ),
    );
  }
  //轮播
  _swiperView(){
    return Container(
      child: Swiper(
        itemCount: bannerList?.length ?? 0,
        loop: false,
        autoplay: false,
        controller: _swiperController,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
              onTap: () {
                BannerModel banner = bannerList[index];
                if (banner.inner) {
                  if (banner.itemType == 1) {
                    NavigatorUtil.push(GoodsDetail(
                      goodsId: '${banner.itemId}',
                    ));
                  } else if (banner.itemType == 4) {
                    VideoUtil.viewVideoDetail(context, banner.itemId);
                  } else if (banner.itemType == 2) {
                    CinemaUtil.viewCinemaDetail(
                        context, banner.itemId, null);
                  } else if (banner.itemType == 3) {
                    NavigatorUtil.push(LifeServiceDetail(
                      itemId: int.parse('${banner.itemId}'),
                    ));
                  }
                } else {
                  NavigatorUtil.push(
                      ViewMain(url: banner.redirectLink));
                }
              },
              child: CachedNetworkImage(
                imageUrl: bannerList[index].banner,
                fit: BoxFit.fill,
              ));
        },
        pagination: SwiperPagination(
          builder: DotSwiperPaginationBuilder(
              color: Colors.white.withAlpha(80),
              activeColor: Colors.white),
        ),
      ),
    );
  }
  //商品类别tab
  _goodsTabBar() {
    if(_goodsCategoryList.isNotEmpty){
      return TabBar(
        controller: _tabController,
        // tabs的长度超出屏幕宽度后,TabBar,是否可滚动
        isScrollable: true,
        // 设置tab文字的类型
        labelStyle: TextStyle(
            fontSize: 15, letterSpacing: 1, fontWeight: FontWeight.w600),
        // 设置tab选中得颜色
        labelColor: JadeColors().claret,
        // 设置tab未选中的颜色
        unselectedLabelColor: JadeColors().grey,
        // 设置tab未选中时文字的类型
        unselectedLabelStyle: TextStyle(fontSize: 15, letterSpacing: 1),
        indicatorWeight: 0.01,
        indicatorColor: Colors.transparent,
        tabs: _goodsCategoryList
            .map((value) => Tab(
          text: value.name,
        )).toList(),
      );
    }else{
      return Container();
    }
  }

  _goodsListView() {
    if(_goodsCategoryList.isNotEmpty){
      return TabBarView(
        controller: _tabController,
        children: _tabViews(),
      );
    }else{
      return Container();
    }
  }

  _tabViews(){
    List<Widget> _tabViewList = [];
    for(int i = 0;i<_goodsCategoryList.length;i++){
      _tabViewList.add(GoodsListPage(categoryParams: _goodsCategoryList[i],index: i,key: Key('$i'),));//传入类别数组的index,
    }
    return _tabViewList;
  }

  void getData() {
    Future.delayed(Duration(seconds: 1), () {
     // 接口请求
 1.banner请求
 2.tabBar数据请求
_httpGoodsCategory();
    });
  }
//商品类别
  _httpGoodsCategory(){
    HttpApplication.getInstance().goodsCategoryList(callBack: (result){
      if(result!=null){
        if(mounted){
          List<GoodsCategoryBean> _dataList = [];
          for(int i = 0; i< result.length; i++){
            GoodsCategoryBean _goodsCategoryBean = GoodsCategoryBean.fromJson(result[i]);
            if(_goodsCategoryBean.parentId == 0){
              _dataList.add(_goodsCategoryBean);
            }
          }
          _goodsCategoryList = _dataList;
          if(_goodsCategoryList.isNotEmpty){
            _tabController = TabController(length: _goodsCategoryList.length, vsync: this);
            _tabController.addListener(() {
              _position = _tabController.index;
            });
            _tabController.index = _position; //保持刷新时,tabBar index不会置为0
          }
          if(!_isFirstIn){
            ATuiEventBusTool.shared().fire({"type":"reset_page_num","viewIndex": _position});
          }
        }
        setState(() {});
        }

    },errorCallBack: (error){
      setState(() {});
    });
  }

  initSliverPersistentHeader() {
    return SliverPersistentHeader(
      //是否固定头布局 默认false
        pinned: false,
        //是否浮动 默认false
        floating: false,
        //必传参数,头布局内容
        delegate: MySliverDelegate(
          //缩小后的布局高度
          minHeight: 40.0,
          //展开后的高度
          maxHeight: Utils().screenWidth(context) * 0.6,
          child: Container(
              color: Colors.white,
              child: _swiperView()),
        ));
  }

  initSliverPersistentHeaderTwo() {
    return SliverPersistentHeader(
      //是否固定头布局 默认false
        pinned: true,
        //是否浮动 默认false
        floating: false,
        //必传参数,头布局内容
        delegate: MySliverDelegate(
          //缩小后的布局高度
          minHeight: 56.0,
          //展开后的高度
          maxHeight: 56.0,
          child: Container(
              color: Colors.white,
              child: _goodsTabBar()),
        ));
  }
  @override
  bool get wantKeepAlive => true;
}

class MySliverDelegate extends SliverPersistentHeaderDelegate {
  MySliverDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });
  final double minHeight; //最小高度
  final double maxHeight; //最大高度
  final Widget child; //子Widget布局

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override //是否需要重建
  bool shouldRebuild(MySliverDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}

2.tabView中子页面GoodsListPage

class GoodsListPage extends StatefulWidget{
  final GoodsCategoryBean categoryParams;
  final physics;
  final index;
  final Key key;
  GoodsListPage({this.categoryParams,this.physics,this.index,this.key}):super(key:key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _GoodsListPage();
  }
}

class _GoodsListPage extends State<GoodsListPage>{

  List<GoodsListModel> _goodsList = [];
  int _page = 1;
  int _pageSize = 20;

  int _viewIndex = 0;
  var _loadType;
  RefreshController refreshController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refreshController = RefreshController();
    _refreshHttp();

	//判断创建时传入的index,是否和通过EvenBus通知过来的tabController.index相等
	//相等则请求接口(只让当前页请求接口,防止每个子页面都请求)
    ATuiEventBusTool.shared().on().listen((event) {
      _viewIndex = event["viewIndex"];
      _loadType = event["type"];
      if(_loadType=="reset_page_num" && _viewIndex ==widget.index){
      _refreshHttp();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      footer: defaultRefreshFooter(),
      controller:refreshController,
      enablePullDown: false,//禁止下拉刷新,防止与主页面冲突
      enablePullUp: true,
      onLoading: ()async{
        _loadMoreHttp();
      },
      child: CustomizeStaggeredGridView.countBuilder(
        crossAxisCount: 4,
        staggeredTileBuilder: (int index) => StaggeredTile.fit(2),
        mainAxisSpacing: 4.0,
        crossAxisSpacing: 4.0,
        itemCount: math.max(0, _goodsList.length * 2 - 1),
        shrinkWrap: true,
        //physics: physics,
        itemBuilder: (_, index) {
          GoodsListModel info = _goodsList[index];
          return GoodsItem(
            index: index,
            item: info,
          );
        },
        separatorBuilder: (_, __) => Container(),
      ),
    );
  }

  _httpGoodsList(){
    var params = {
      "goodsCategoryParentId": widget.categoryParams.id,
      "pageNum": _page,
      "pageSize": _pageSize, //默认20条
      "sort": 1
    };
    HttpApplication.getInstance().goodsList(params,callBack: (result){
      if(result != null){
        if(mounted){
          List<GoodsListModel> _resultList = [];
          var dataList = result['list'];
          for(int i = 0; i< dataList.length; i++){
            GoodsListModel _goodsListModel = GoodsListModel.fromJson(dataList[i]);
            _resultList.add(_goodsListModel);
          }
          if(_page == 1){
            _goodsList = _resultList;
            setState(() {});
          }else{
            _goodsList.addAll(_resultList);
            setState(() {});

            Future.delayed(Duration(microseconds: 500),(){
              if(_resultList.length < _pageSize){
                //没有更多数据
                if (refreshController.isLoading) {
                  refreshController.loadNoData();
                }
              }else{
                if (refreshController.isLoading) {
                  refreshController.loadComplete();
                }
              }
            });
          }
        }
        }
    },errorCallBack: (error){
      setState(() {});
    });
  }

  _refreshHttp(){
    _page = 1;
    _httpGoodsList();
  }
  _loadMoreHttp(){
    _page ++;
    _httpGoodsList();
  }
}
### Flutter 中实现小红书风格吸顶效果 在 Flutter 中,可以通过 `SliverAppBar` 和自定义滚动控制器来实现类似于小红书的吸顶效果。这种效果通常用于列表中的某些部分固定在屏幕顶部,当用户继续向下滚动时保持可见。 以下是具体的实现方法: #### 使用 SliverAppBar 实现吸顶效果 Flutter 提供了一个强大的布局组件叫做 `CustomScrollView`,它允许开发者通过组合多个 slivers 来构建复杂的滚动界面。其中,`SliverAppBar` 是一种可以随着滚动而变化高度或者固定的组件[^2]。 下面是一个简单的例子展示如何使用 `SliverAppBar` 创建吸顶效果: ```dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ // 吸顶栏 SliverAppBar( pinned: true, // 设置为true使头部固定不消失 expandedHeight: 100.0, flexibleSpace: FlexibleSpaceBar( title: Text('小红书风格吸顶'), ), ), // 列表项 SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return ListTile(title: Text('Item $index')); }, childCount: 50, ), ) ], ), ), ); } } ``` 在这个示例中,我们创建了一个带有吸顶功能的应用程序页面。`pinned: true` 参数确保即使用户向上滑动,应用栏仍然会停留在屏幕上[^3]。 #### 自定义 Sticky Header 的实现方式 如果需要更复杂的效果(比如不同的分区有不同的吸顶头),则可能需要用到第三方包如 **flutter_sticky_header** 或者手动编写逻辑处理不同区域间的切换行为。 这里给出一个基于 flutter_sticky_header 插件的例子: 首先,在 pubspec.yaml 文件里添加依赖: ```yaml dependencies: sticky_headers: ^0.1.8+1 ``` 接着导入并使用该插件: ```dart import 'package:flutter/material.dart'; import 'package:sticky_headers/sticky_headers/widget.dart' as sh; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { final List<String> sections = ['A', 'B', 'C']; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Sticky Headers Example')), body: ListView.builder( itemCount: sections.length, itemBuilder: (_, i) => Column( children: [ sh.StickyHeader( header: Container( height: 50.0, color: Colors.blueGrey[700], padding: EdgeInsets.symmetric(horizontal: 16.0), alignment: Alignment.centerLeft, child: Text(sections[i], style: TextStyle(color: Colors.white)), ), content: Container( child: ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemCount: 20, itemBuilder: (_, j) => ListTile(title: Text('${sections[i]} item #$j')), ), ), ), ], ), ), ), ); } } ``` 此代码片段展示了如何在一个视图内设置多个可独立滚动的部分,并让每个部分都有自己的吸顶标题[^4]。 ### 总结 以上两种方案分别适用于简单场景下的全局吸顶以及较为复杂的分组数据局部吸顶需求。对于像小红书这样的社交平台来说,后者更为贴近实际业务需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值