Flutter 瀑布流如何仿寫原生的複用機制?

頭疼腦脹的程式碼搬運工發表於2021-07-28

廢話開篇:iOS與android在實現列表介面的時候是有重用機制的,目的就是減少記憶體開銷,用時間換空間。個人感覺flutter並沒有特別強調複用,關於listView.builder 的“複用”個人感覺應該是銷燬跟重建的過程,所以這裡用flutter實現了簡單的複用機制。程式碼拙劣,大神勿噴,共同進步

先看複用效果

image.png

複用狀態列印

image.png

右側是簡單實現瀑布流介面,裡面顯示的是一共有39個Widget。左側是控制檯列印一共建立的12個Widget,所以這裡就簡單的實現了Widget複用。

問題一、實現思路是什麼?

這裡先簡單的說一下實現思路。

  1. 在渲染介面前,通過計算得出全部的Widget的位置座標。
  2. 首次渲染建立一屏可視瀑布流Widget.
  3. 監聽滑動,判斷當前頁面滾動方向展示的瀑布流Widget,先去快取池裡拿,如果沒有就直接建立,新增到元件中進行渲染。如果快取池裡有,修改Widget的相對佈局位置。

問題二、UI佈局程式碼分析。

image.png

tip: WaterfallFlow.dart 瀑布流主頁面;WaterfallFlowItem.dart 瀑布流單元item

效果展示:

Simulator Screen Shot - iPhone 11 - 2021-07-28 at 16.54.44.png

WaterfallFlowItem.dart 瀑布流item檔案

class WaterfallFlowItem extends StatefulWidget{
  Frame? _frame;
  WaterfallFlowItemState? _waterfallFlowItemState;

  WaterfallFlowItem({required Frame frame}){
    _frame = frame;
  }

  Frame getFrame(){
    return _frame!;
  }

  void setFrame({required Frame frame}) {
    _frame = frame;
    _waterfallFlowItemState!.setFrame(frame: frame);
  }

  @override
  State<StatefulWidget> createState() {
    _waterfallFlowItemState = new WaterfallFlowItemState(frame: _frame!);
    return _waterfallFlowItemState!;
  }
}

class WaterfallFlowItemState extends State<WaterfallFlowItem> with AutomaticKeepAliveClientMixin {
  Frame? _frame;

  WaterfallFlowItemState({required Frame frame}){
    _frame = frame;
  }

  void setFrame({required Frame frame}) {
    setState(() {
      _frame = frame;
    });
  }
  @override
  Widget build(BuildContext context) {
    return new Positioned(
        top: _frame!.top,
        left: _frame!.left,
        child: GestureDetector(
          child: new Container(
            color: _frame!.index == 12 ? Colors.red : Color.fromARGB(255, 220, 220, 220),
            width: _frame!.width,
            height: _frame!.heigth,
            child: new Text(_frame!.index.toString()),
          ),
          onTap: (){

          },
        )
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
複製程式碼

WaterfallFlow.dart 主介面檔案

builder 實現

@override
Widget build(BuildContext context) {
  return new Container(
    //去掉scrollView頂部空白間隙
    child: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: Scrollbar(
          //isAlwaysShown: true,
          //showTrackOnHover: true,
          //scrollView
          child: new SingleChildScrollView(
            controller: _scrollController,
            child: new Container(
              width: MediaQuery.of(context).size.width,
              //最大高度
              height: _maxHeight,
              color: Colors.white,
              child: new Stack(
                //幀佈局下的瀑布流單元格item集合
                children: _listWidget,
              ),
            ),
          ),
        )
  ),
  );
}
複製程式碼

宣告的屬性

//瀑布流間隔
double sep = 5;
//瀑布流寬度
double? _width;
//最大高度
double _maxHeight = 0;
//左側最大高度
double leftHeight = 0;
//右側最大高度
double rightHeight = 0;
//主介面高度
double _mineContentHeight = 0;
//瀑布流item快取池
List<WaterfallFlowItem> _bufferPoolWidget = [];
//當前顯示的瀑布流item
List<WaterfallFlowItem> _listWidget = [];
//當前組渲染frame物件儲存
List<Frame> _fList = [];
//總frame集合
List<Frame> _frameList = [];
//資料來源這裡只儲存高度
List<double> _list = [
  100,150,45,11,140,89,212,21,434,545,100,150,45,11,140,89,212,21,434,545,
  100,150,45,11,140,89,212,21,434,545,100,150,45,11,140,89,212,21,434,545];
//滑動監聽
ScrollController _scrollController = new ScrollController();
//滑動偏移量
double _scrollOff = 0;
複製程式碼

計算主視窗scrollView 高度

//獲取最大高度,並計算出全部的瀑布流位置
void getMaxHeight(){
  List<Frame> fList = [];
  double width = (_width! - sep * 3) / 2.0;
  double maxHeight = _maxHeight;
  for(int i = _frameList.length;i < _list.length;i++){
    double height = _list[i];
    bool isLeft = (leftHeight <= rightHeight);
    double left = isLeft ? sep : (width + sep * 2);
    maxHeight = isLeft ? leftHeight : rightHeight;
    Frame frame = Frame(leftP: left, topP: maxHeight, widthP: width, heigthP: height,indexP: i);
    if(isLeft == true) {
      leftHeight += (height + sep);
    } else {
      rightHeight += (height + sep);
    }
    fList.add(frame);
  }
  _maxHeight = max(leftHeight, rightHeight);
  _frameList.addAll(fList);
  //重新整理
  setState(() {});
}
複製程式碼

Frame 位置資訊類

class Frame{
  double left = 0;//左
  double top = 0;//右
  double width = 0;//寬度
  double heigth = 0;//高度
  int index = 0;//索引
  Frame({required leftP
  ,required topP,
    required widthP,
    required heigthP,
    required indexP}){
    left = leftP * 1.0;
    top = topP * 1.0;
    width = widthP * 1.0;
    heigth = heigthP * 1.0;
    index = indexP;
  }
}
複製程式碼

生成瀑布流Widget單元item

//重用池裡生成item
_takeReuseFlowItem(Frame f,dynamic block){
  WaterfallFlowItem? waterfallFlowItem;
  //是否重用,是,直接修改frame;否,重新渲染。
  bool isReUse = false;
  //有,從快取池裡取(快取中的已在結構樹裡,可以修改幀佈局位置)
  if(_bufferPoolWidget.length > 0){
    waterfallFlowItem = _bufferPoolWidget.last;
    waterfallFlowItem.setFrame(frame: f);
    _bufferPoolWidget.removeLast();
    isReUse = true;
  }
  
  //沒有,直接建立(不快取中的,需要呼叫setState方法渲染)
  if(waterfallFlowItem == null) {
    waterfallFlowItem = new WaterfallFlowItem(frame: f,);
    isReUse = false;
  }
  block(waterfallFlowItem,isReUse);
}
複製程式碼

建立首屏全部可視瀑布流Widget單元元件

//渲染瀑布流item
createWaterfallFlow(int index){
  getMaxHeight();
  //這裡加點延遲,保證獲取最大高度完成(不太嚴謹,大神有好方法請賜教[抱拳])
  Future.delayed(Duration(milliseconds: 100),(){
    _mineContentHeight = context.size!.height;
    for(var i = 0;i < _frameList.length;i++){
      Frame f = _frameList[i];
      //判斷視覺化邏輯
      if(f.top <= _mineContentHeight + _scrollOff) {
        _takeReuseFlowItem(f,(WaterfallFlowItem waterfallFlowItem,bool isReuse){
          _listWidget.add(waterfallFlowItem);
        });
      }
    }
    setState(() {
    });
  });
}
複製程式碼

滑動過程中進行重用渲染

//獲取上滑狀態當前顯示的下一個item位置
Frame? _getUpNeedShowFrame(){
  Frame? f;
  WaterfallFlowItem? lastWaterfallFlowItem = _listWidget.last;
  if(lastWaterfallFlowItem.getFrame().index + 1 < _frameList.length) {
    f = _frameList[lastWaterfallFlowItem.getFrame().index + 1];
  }
  return f;
}

//獲取下滑狀態當前顯示的上一個item位置
Frame? _getDownNeedShowFrame(){
  Frame? f;
  WaterfallFlowItem? lastWaterfallFlowItem = _listWidget[0];
  if(lastWaterfallFlowItem.getFrame().index - 1 >= 0) {
    f = _frameList[lastWaterfallFlowItem.getFrame().index - 1];
  }
  return f;
}

//超出介面可視範圍的瀑布流加入快取池
void addFlowItemAddToBufferPool(){

  List<WaterfallFlowItem> list = [];
  for(int i = 0; i < _listWidget.length;i++){
    WaterfallFlowItem? waterfallFlowItem = _listWidget[i];
    Frame? frame = waterfallFlowItem.getFrame();
    if((frame.top + frame.heigth) <  _scrollOff || frame.top > _mineContentHeight + _scrollOff) {
      _bufferPoolWidget.add(waterfallFlowItem);
      list.add(waterfallFlowItem);
    }
  }
  if(list.length != 0) {
    for(int i= 0;i < list.length;i++){
      WaterfallFlowItem? waterfallFlowItem = list[i];
      if(_listWidget.contains(waterfallFlowItem)){
        _listWidget.remove(waterfallFlowItem);
      }
    }
  }

  //從快取池裡獲取item
  //上滑狀態
  Frame? upNextFrame = _getUpNeedShowFrame();
  if(upNextFrame != null) {
    //debugPrint('我是在複用 ${upNextFrame.index} ,${upNextFrame.top},${_mineContentHeight + _scrollOff}');
    if(upNextFrame.top <= _mineContentHeight + _scrollOff) {
      debugPrint('我在上滑重置第${upNextFrame.index}個frame');
      _takeReuseFlowItem(upNextFrame,(WaterfallFlowItem waterfallFlowItem,bool isReuse){
        _listWidget.add(waterfallFlowItem);
        if(!isReuse){
          debugPrint('我不是複用');
          setState(() {});
        } else {
          debugPrint('我是複用');
          waterfallFlowItem.setFrame(frame: upNextFrame);
        }
      });
    }
  }

  //下滑狀態
  Frame? downNextFrame = _getDownNeedShowFrame();
  if(downNextFrame != null) {
    //debugPrint('我是在複用 ${downNextFrame.index} ,${downNextFrame.top},${_mineContentHeight + _scrollOff}');
    if(downNextFrame.top + downNextFrame.heigth > _scrollOff && downNextFrame.top + downNextFrame.heigth < _mineContentHeight + _scrollOff) {
      debugPrint('我在下滑重置第${downNextFrame.index}個frame');
      _takeReuseFlowItem(downNextFrame,(WaterfallFlowItem waterfallFlowItem,bool isReuse){
        _listWidget.insert(0, waterfallFlowItem);
        if(!isReuse){
          debugPrint('我不是複用');
          setState(() {});
        } else {
          debugPrint('我是複用');
          waterfallFlowItem.setFrame(frame: downNextFrame);
        }
      });
    }
  }
}
複製程式碼

滾動監聽

_scrollController.addListener(() {
  _scrollOff = _scrollController.offset;
  //加入快取池,並進行復用
  addFlowItemAddToBufferPool();
  debugPrint('總共:${_listWidget.length + _bufferPoolWidget.length} 個');
});
複製程式碼

基本上flutter的瀑布流複用邏輯就完成了,程式碼拙劣,裡面有些地方需要優化,比如:快速滑動防護,item的內容渲染。flutter對於介面渲染已經很極致了,重寫複用有點倒退的趕腳。大神勿噴,互相學習。[抱拳][抱拳][抱拳]

相關文章