Flutter瀑佈流仿寫原生的復用機制詳解

廢話開篇:

iOS與android在實現列表界面的時候是有重用機制的,目的就是減少內存開銷,用時間換空間。個人感覺flutter並沒有特別強調復用,關於listView.builder 的“復用”個人感覺應該是銷毀跟重建的過程,所以這裡用flutter實現瞭簡單的復用機制。代碼拙劣,大神勿噴,共同進步

先看復用效果

復用狀態打印

右側是簡單實現瀑佈流界面,裡面顯示的是一共有39個Widget。左側是控制臺打印一共創建的12個Widget,所以這裡就簡單的實現瞭Widget復用。

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

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

  • 在渲染界面前,通過計算得出全部的Widget的位置坐標。
  • 首次渲染創建一屏可視瀑佈流Widget.
  • 監聽滑動,判斷當前頁面滾動方向展示的瀑佈流Widget,先去緩存池裡拿,如果沒有就直接創建,添加到組件中進行渲染。如果緩存池裡有,修改Widget的相對佈局位置。

問題二、UI佈局代碼分析。

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

效果展示:

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對於界面渲染已經很極致瞭,重寫復用有點倒退的趕腳。大神勿噴,互相學習。

總結

到此這篇關於Flutter瀑佈流仿寫原生的復用機制的文章就介紹到這瞭,更多相關Flutter仿寫復用機制內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: