草庐IT

Flutter吸顶Tabbar+流式布局

XDJcc 2023-03-28 原文

实现APP首页tabbar滚动吸顶功能

首页代码:

           WillPopScope(
            child: Scaffold(
              backgroundColor: Colors.white,
              appBar: PreferredSize(
                preferredSize: Size(double.infinity, 0.w),
                child: AppBar(
                  backgroundColor: Colors.transparent,
                  shadowColor: Colors.transparent,
                  elevation: 0,
                  title: const Text(""),
                ),
              ),
              body: NestedScrollView(
                controller: scrollController,
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) {
                  return <Widget>[
                    buildHeaderWidget(), // tabbar上面被隐藏的部分
                    SliverOverlapAbsorber(
                      handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                          context),
                      sliver: SliverPersistentHeader(
                        pinned: true,
                        // floating: true,
                        delegate: StickyTabBarDelegate(
                          child: BrnTabBar(  //生成tabbar
                            controller: tabController,
                            tabs: tabs, 
                            showMore: true,
                            moreWindowText: "栏目总览",
                            onTap: (state, index) {
                              state.refreshBadgeState(index);
                              // scrollController.animateTo(
                              //     globalKey.currentContext!.size!.height,
                              //     duration: Duration(milliseconds: 200),
                              //     curve: Curves.linear);
                            },
                            onMorePop: () {},
                            closeController: closeWindowController,
                          ),
                        ),
                      ),
                    ),
                    SliverToBoxAdapter(
                      child: SizedBox(
                        height: 60.w,
                      ),
                    )
                  ];
                },
                body: TabBarView(
                  controller: tabController,
                  children: catTabList.map<Widget>((e) {
                    return HomeArticlesListPage(e.id,
                        showTopContainer: showTopContainer);
                  }).toList(),
                ),

                //
              ),
            ),
            onWillPop: () {
              if (closeWindowController!.isShow) {
                closeWindowController!.closeMoreWindow();
                return Future.value(false);
              }
              return Future.value(true);
            },
          );

tabbar下 各页面流式布局代码:

流式布局使用的是 MasonryGridView.count();
因为是要在tabbar下的页面 所以 要关闭滚动 且不能绑定 controller;
绑定controller会导致 首页有滚动事件滚动首页部分
流式布局组件滚动流式布局的界面 然会吸顶 就会失效。

我一开始就犯了这个错误  虽然设置了 physics: const NeverScrollableScrollPhysics(),
让流式布局不滚动 但是忘记去除绑定的 controller 就导致吸顶的动画出错了。

import 'package:communityApp/app/router/routers.dart';
import 'package:communityApp/app/utils/local_storage.dart';
import 'package:communityApp/components/cache_Image_widget.dart';
import 'package:communityApp/home_system/request/homeRequest.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class HomeArticlesListPage extends StatefulWidget {
  final int activeCatId; //当前选择的栏目ID
  Function? showTopContainer;
  HomeArticlesListPage(this.activeCatId, {Key? key, this.showTopContainer})
      : super(key: key);

  @override
  State<HomeArticlesListPage> createState() => _HomeArticlesListPageState();
}

class _HomeArticlesListPageState extends State<HomeArticlesListPage> {
  late ScrollController _scrollViewController;
  List _buildArticleList = []; // 瀑布留 数据列表
  bool _isOver = true; // 接口请求 防抖
  int _page = 1; //当前的页数
  bool _haveMore = true; //是否有更多的数据

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

    _scrollViewController = ScrollController(initialScrollOffset: 0.w)
      ..addListener(() {
        // print(_scrollViewController.position.pixels);
        // if (_scrollViewController.position.pixels < 10) {
        //   widget.showTopContainer == null ? '' : widget.showTopContainer!(0.0);
        // } else {
        //   widget.showTopContainer == null ? '' : widget.showTopContainer!(-1.0);
        // }
        // 当滚动到最底部的时候,加载新的数据
        if (_scrollViewController.position.pixels ==
            _scrollViewController.position.maxScrollExtent) {
          //当还有更多数据的时候才会进行加载新数据
          if (_haveMore) {
            _getListViewList();
          }
        }
      });
    _getListViewList();
  }

  // 加载更多 数据
  void _getListViewList() async {
    if (!_isOver) return;
    _isOver = false;
    if (_haveMore) {
      var userId = await LocalStorage.get(LocalStorage.userId);
      var result = await HomeRequest.getArticleList({
        'userId': userId,
        'articleCatId': widget.activeCatId,
        'pageSize': 10,
        'pageNum': _page
      });
      _isOver = true;
      if (mounted) {
        setState(() {
          if (_page == 1) {
            _buildArticleList = result;
          } else {
            _buildArticleList.addAll(result);
          }
          if (result.length == 10) {
            _page++;
          } else if (result.length < 10) {
            _haveMore = false;
          }
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    return Container(
      padding: EdgeInsets.fromLTRB(20.w, 0.w, 20.w, 60.w),
      child: MasonryGridView.count(
        // controller: _scrollViewController,
        // 展示几列
        crossAxisCount: 2,
        // 元素总个数
        itemCount: _buildArticleList.length,
        // 单个子元素
        itemBuilder: (BuildContext context, int index) {
          var item = _buildArticleList[index];
          var user = item['user'];
          return GestureDetector(
            onTap: () async {
              /* 跳转 */
              if (item["type"] == 1) {
                /* 跳转到动态 */
                var result = await Navigator.of(context).pushNamed(
                    CommunityAppRouter.articelDetailPage,
                    arguments: {"articleId": item["id"].toString()});
              } else {
                var result = await Navigator.of(context).pushNamed(
                    CommunityAppRouter.evaluationDetailPage,
                    arguments: {"articleId": item["id"].toString()});
              }
            },
            child: Container(
              child: Column(
                children: [
                  Container(
                    clipBehavior: Clip.hardEdge, //溢出隐藏c
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.w),
                    ),
                    child: CaCheImageWidget(
                      item['frontCover'],
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.all(8.w),
                    child: Text(
                      item['title'],
                      overflow: TextOverflow.ellipsis,
                      maxLines: 2,
                      style: TextStyle(
                        color: const Color.fromARGB(255, 0, 0, 0),
                        fontSize: 15.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.fromLTRB(8.w, 0, 8.w, 8.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                          width: 110.w,
                          decoration: BoxDecoration(),
                          clipBehavior: Clip.hardEdge,
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              ClipOval(
                                child: CaCheImageWidget(
                                  user['picture'],
                                  width: 14.w,
                                  height: 14.w,
                                ),
                              ),
                              Container(
                                width: 90.w,
                                margin: EdgeInsets.only(left: 4.w),
                                child: Text(
                                  user['nickName'],
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                  style: TextStyle(
                                    color: Color(0xFFB3BBBD),
                                    fontSize: 11.sp,
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                        Container(
                          child: Text(
                            '${item['viewNum']}看过',
                            style: TextStyle(
                              color: const Color(0xFFB3BBBD),
                              fontSize: 11.w,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        },
        // 纵向元素间距
        mainAxisSpacing: 10,
        // 横向元素间距
        crossAxisSpacing: 10,
        //本身不滚动,让外面的singlescrollview来滚动
        physics: const NeverScrollableScrollPhysics(),
        shrinkWrap: true, //收缩,让元素宽度自适应
      ),
    );
  }

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

有关Flutter吸顶Tabbar+流式布局的更多相关文章

  1. ruby - nanoc 和多种布局 - 2

    是否可以为特定(或所有)项目使用多个布局?例如,我有几个项目,我想对其应用两种不同的布局。一个是绿色的,一个是蓝色的(但是)。我想将它们编译到我的输出目录中的两个不同文件夹中(例如v1和v2)。我一直在玩弄规则和编译block,但我不知道这是怎么回事。因为,每个项目在编译过程中只编译一次,我不能告诉nanoc第一次用layout1编译,第二次用layout2编译。我试过这样的东西,但它导致输出文件损坏。compile'*'doifitem.binary?#don’tfilterbinaryitemselsefilter:erblayout'layout1'layout'layout2'

  2. ruby - 带有 header 的 Sinatra 流式响应 - 2

    我想通过Sinatra应用程序代理远程文件。这需要将带有header的HTTP响应从远程源流式传输回客户端,但我不知道如何在Net::HTTP#提供的block内使用流式API时设置响应header获取响应。例如,这不会设置响应头:get'/file'dostreamdo|out|uri=URI("http://manuals.info.apple.com/en/ipad_user_guide.pdf")Net::HTTP.get_response(uri)do|file|headers'Content-Type'=>file.header['Content-Type']file.re

  3. ruby - 使用 Ruby 将 HTTP GET 的响应主体流式传输到 HTTP POST - 2

    我正在尝试下载一个大文件,然后使用Ruby将该文件发布到REST端点。该文件可能非常大,即超过可以存储在内存中甚至磁盘上的临时文件中的容量。我一直在用Net::HTTP尝试这个,但我愿意接受任何其他库(rest-client等)的解决方案,只要他们做我想做的事情。这是我尝试过的:require'net/http'source_uri=URI("https://example.org/very_large_file")source_request=Net::HTTP::Get.new(source_uri)source_http=Net::HTTP.start(source_uri.ho

  4. Ruby AWS::S3::S3Object (aws-sdk):是否有与 aws-s3 一样的流式数据方法? - 2

    在aws-s3中,有一种方法(AWS::S3::S3Object.stream)可让您将S3上的文件流式传输到本地文件。我无法在aws-sdk中找到类似的方法。即在aws-s3中,我这样做:File.open(to_file,"wb")do|file|AWS::S3::S3Object.stream(key,region)do|chunk|file.writechunkendendAWS::S3:S3Object.read方法确实将block作为参数,但似乎没有对其执行任何操作。 最佳答案 aws-sdkgem现在支持S3中对象的分

  5. Flutter 环境变量配置和flutter doctor中的错误解决 - 2

    一、环境变量右键点击我的电脑-属性:然后找到环境变量 1.Android的SDK不在C盘的话需要额外配这个到用户环境变量:ANDROID_HOMED:\AndroidSDK2.然后在系统变量:Path中添加一条这样的值        D:\Flutter\flutter\bin             这个值写flutter包解压的实际地址即可 3.在系统变量中添加两个镜像变量:        变量名:FLUTTER_STORAGE_BASE_URL      变量值:https://storage.flutter-io.cn        变量名:PUB_HOSTED_URL      变量

  6. ruby-on-rails - 我可以在没有 Controller 的情况下直接从 routes.rb 渲染布局吗? - 2

    我想为网站的管理和公共(public)部分设置一对样式指南。每个都需要自己的布局,其中包含静态html和调用erbpartials的混合(因此静态页面不会削减它)。我不需要Controller来为这些页面提供服务,而且我不希望有效的仅开发内容使其余代码困惑。这让我想知道是否有一种方法可以直接呈现布局。免责声明:我明白这不是我应该经常/永远做的事情,而且我知道有很多争论可以解释为什么这是一个坏主意。我对这是否可能感兴趣。有没有办法让我直接从routes.rb渲染布局而不通过Controller? 最佳答案 出于某种奇怪的原因,我想暂时

  7. ruby-on-rails - 设计 Controller 如何改变布局? - 2

    这个问题在这里已经有了答案:differentlayoutforsign_inactionindevise(8个答案)关闭7年前。如何更改设计Controller中的布局?

  8. ruby-on-rails - Rails - 如何在布局中查找域 url - 2

    我有request.env['http_host']在本地主机上工作,但在heroku的布局页面中引用时会导致错误。此请求在View中工作并显示正确的基本url,但是当我将代码移动到布局时它会导致错误。注意-我正在使用它来为html电子邮件中的图像构建绝对url。收到错误:ActionView::Template::Error(undefinedmethod`env'fornil:NilClass): 最佳答案 如果你想要没有端口的主机,只需使用:request.host编辑:糟糕,我刚刚注意到您正在使用View中的代码。我不知道它

  9. ruby - 从 Amazon S3 流式传输动态 zip - 2

    我正在寻找一种从AmazonS3动态流式下载zip文件的方法。应用程序托管在EC2上,文件存储在S3上。需要让用户能够从一组文件中进行选择,然后将这些文件打包并下载给他们。听说过一些可能可行的Actionscript库(aszip和fzip),或者可以在Ruby或什至PHP中执行此操作。文件不需要任何压缩,zip只是用于将文件捆绑到一个下载中.... 最佳答案 我使用NginxZipModule流式传输本地文件,但可以选择从远程位置流式传输。否则,您可以将它与VFS安装的S3存储一起用作本地文件系统。支持seek-断点续传和加速下载

  10. Ruby GUI(非复杂布局) - 2

    我对RubyGUI设计做了很多研究,这似乎是Ruby倾向于落后的领域。我探索了MonkeyBars、wxRuby、fxRuby、Shoes等选项,只是想从Ruby社区获得一些意见。虽然它们绝对可用,但每一个的开发似乎都在下降。我在任何(减去fxRuby书)上都找不到大量有用的文档或用户基础。我只是想制作一个简单的GUI,所以我真的不想花费数百小时来学习更复杂的工具的复杂性或尝试使用甚至不再开发的东西(鞋子是应用程序的类型我正在寻找,但它有很多问题并且没有得到积极开发。)在所有选项中,你们会推荐哪个选项是最快的,并且仍然具有某种开发基础?谢谢! 最佳答案

随机推荐