Flutter吸頂Tabbar+流式佈局

来源:https://www.cnblogs.com/XDJcc/archive/2022/07/05/16447389.html
-Advertisement-
Play Games

實現APP首頁tabbar滾動吸頂功能 首頁代碼: WillPopScope( child: Scaffold( backgroundColor: Colors.white, appBar: PreferredSize( preferredSize: Size(double.infinity, 0. ...


實現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();
  }
}


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 目錄 一、前景回顧 二、實現中斷框架 三、代碼實現 四、中斷的壓棧和出棧過程分析 五、運行測試 一、前景回顧 前面我們已經講解了中斷的基本知識,接下來要開始進行代碼的實操。代碼主要有兩塊,其中一塊是關於可編程中斷控制器8259A的代碼,另一塊主要是整個中斷的代碼。 二、實現中斷框架 IDT:中斷描述 ...
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 Ubuntu20.04伺服器版安裝 下載地址:https://ubuntu.com/download/desktop 一、語言選擇:English(按Done確認,Done按鈕在安裝視窗的最下麵) 二、Installer update avail ...
  • 鏡像下載、功能變數名稱解析、時間同步請點擊 阿裡雲開源鏡像站 OneForAll是一款功能強大的子域收集工具 我安裝到了kali git clone https://gitee.com/shmilylty/OneForAll.git git clone https://github.com/shmilylt ...
  • 本文會介紹如何安裝和部署ClickHouse,官方推薦的幾種安裝模式,以及安裝之後如何啟動,ClickHouse集群如何配置等。 簡單來說,ClickHouse的搭建流程如下: 環境檢查,環境依賴安裝 在對應的服務上下載安裝Click House 配置config.xml和user.xml,如果搭建 ...
  • mysql拆分字元串作為查詢條件 有個群友問一個問題 這表的ancestors列存放的是所有的祖先節點,以,分隔 例如我查詢dept_id為103的所有祖先節點,現在我只有一個dept_id該怎麼查 然後我去網上找到這樣一個神奇的sql,改改表名就成了下麵的這樣 SELECT substring_i ...
  • 在如今的業務場景下,高可用性要求越來越高,核心業務跨可用區已然成為標配。騰訊雲資料庫高級工程師劉家文結合騰訊雲資料庫的內核實戰經驗,給大家分享Redis是如何實現多可用區,內容包含Redis主從版、集群版原生架構,騰訊雲Redis集群模式主從版、多AZ架構實現以及多AZ關鍵技術點,具體可分為以下四個 ...
  • 本文主要介紹無損壓縮圖片的概要流程和原理,以及lepton無損壓縮在前期調研中遇到的問題。 ...
  • 安卓往系統中添加日程提醒,吭比較多。 首先有個需求(仿製 ios 日曆),為什麼仿製ios呢?這個得問產品了,我只是一個搬磚的程式員 (*´艸`) 捂嘴 大致有日期,時間,重覆設置,自定義重覆設置,位置提醒設置 跟系統日曆的設置類似,畢竟需要同步到系統,所以設置上面保持規範,都是設置好日期時間,然後 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...