flutter-兩個(gè)列表之間元素拖拽

  • 首先需要完成一個(gè)GridView內(nèi)的元素拖拽交換位置;
  • 然后解決兩個(gè)GridView之間拖拽的數(shù)據(jù)問(wèn)題.(ListView同理)

class CategoriesDragTestPage extends StatefulWidget {
  CategoriesDragTestPage({Key key}) : super(key: key);

  @override
  _CategoriesDragTestPageState createState() => _CategoriesDragTestPageState();
}

class _CategoriesDragTestPageState extends State<CategoriesDragTestPage> {
  List<String> _data1List = ["1-1", "1-2", "1-3", "1-4", "1-5", "1-6", "1-7"];
  List<String> _data2List = ["2-1", "2-2", "2-3", "2-4", "2-5", "2-6", "2-7"];

  int _data1WillAcceptIndex = -1;
  bool _data1howItemWhenCovered = false; //手指覆蓋的地方,即item被拖動(dòng)時(shí) 底部的那個(gè)widget是否可見;
  List<String>
      _data1ListBackup; //數(shù)據(jù)源備份,在拖動(dòng)時(shí) 會(huì)直接在數(shù)據(jù)源上修改 來(lái)影響UI變化,當(dāng)拖動(dòng)取消等情況,需要通過(guò)備份還原

  int _data2WillAcceptIndex = -1;
  bool _data2howItemWhenCovered = false; //手指覆蓋的地方,即item被拖動(dòng)時(shí) 底部的那個(gè)widget是否可見;
  List<String>
      _data2ListBackup; //數(shù)據(jù)源備份,在拖動(dòng)時(shí) 會(huì)直接在數(shù)據(jù)源上修改 來(lái)影響UI變化,當(dāng)拖動(dòng)取消等情況,需要通過(guò)備份還原
  int startData1Index = -1;
  int startData2Index = -1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Container(
          child: Column(children: [
            Container(
              height: ScreenUtil().screenHeight / 2,
              child: GridView.builder(
                  itemCount: _data1List.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 5,
                      crossAxisSpacing: 5,
                      mainAxisSpacing: 5,
                      childAspectRatio: 1.0),
                  itemBuilder: (BuildContext context, index) {
                    return _createImg1Widget(index);
                  }),
            ),
            Expanded(
              child: GridView.builder(
                  itemCount: _data2List.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 5,
                      crossAxisSpacing: 5,
                      mainAxisSpacing: 5,
                      childAspectRatio: 1.0),
                  itemBuilder: (BuildContext context, index) {
                    return _createImg2Widget(index);
                  }),
            ),
          ]),
        ));
  }

  Widget _createImg1Widget(int index) {
    return LongPressDraggable(
      data: index,
      child: DragTarget<int>(
        //松手時(shí) 如果onWillAccept返回true 那么就會(huì)調(diào)用,本案例不使用。
        onAccept: (int data) {},
        //繪制widget
        builder: (context, data, rejects) {
          return _data1WillAcceptIndex >= 0 && _data1WillAcceptIndex == index
              ? null
              : _itemWidget(_data1List[index]);
        },
        // 手指拖著一個(gè)widget從另一個(gè)widget頭上滑走時(shí)會(huì)調(diào)用
        onLeave: (data) {
          print('1===$data is Leaving item $index');
          if (startData2Index != -1) {
            startData2Index = -1;
            return;
          }
          _data1WillAcceptIndex = -1;
          setState(() {
            _data1howItemWhenCovered = false;
            _data1List = _data1ListBackup;
          });
        },
        //接下來(lái)松手 是否需要將數(shù)據(jù)給這個(gè)widget  因?yàn)樾枰谕蟿?dòng)時(shí)改變UI,所以在這里直接修改數(shù)據(jù)源
        onWillAccept: (int fromIndex) {
          print('1===$index will accept item $fromIndex');
          bool accept = false;
          if (fromIndex < _data1List.length && startData2Index == -1) {
            //本列表內(nèi)移動(dòng)
            if (_data1WillAcceptIndex != -1) {
              fromIndex = _data1WillAcceptIndex;
            }
            final accept = fromIndex != index;
            if (accept) {
              _data1WillAcceptIndex = index;
              _data1howItemWhenCovered = true;
              _data1List = _data1ListBackup;
              final fromData = _data1List[fromIndex];
              setState(() {
                _data1List.removeAt(fromIndex);
                _data1List.insert(index, fromData);
                print(_data1List);
              });
            }
          } else {
            accept = true;
            //兩個(gè)列表間的移動(dòng)
            if (accept) {
              _data1WillAcceptIndex = index;
              _data1howItemWhenCovered = true;
              final fromData = _data2List[fromIndex];
              setState(() {
                _data2List.removeAt(fromIndex);
                _data1List.insert(index, fromData);
              });
            }
          }
          _data1ListBackup = _data1List;
          _data2ListBackup = _data2List;
          return accept;
        },
      ),
      onDragStarted: () {
        //開始拖動(dòng),備份數(shù)據(jù)源
        _data1ListBackup = _data1List;
        _data2ListBackup = _data2List;
        startData1Index = index;
        print('1===item $index ---------------------------onDragStarted');
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        print(
            '1===item $index ---------------------------onDraggableCanceled,velocity = $velocity,offset = $offset');
        //拖動(dòng)取消,還原數(shù)據(jù)源
        setState(() {
          _data1WillAcceptIndex = -1;
          _data1howItemWhenCovered = false;
          _data1List = _data1ListBackup;
          startData1Index = -1;
          _data2WillAcceptIndex = -1;
          _data2howItemWhenCovered = false;
          _data2List = _data2ListBackup;
        });
      },
      onDragCompleted: () {
        //拖動(dòng)完成,刷新狀態(tài),重置willAcceptIndex
        print("1===item $index ---------------------------onDragCompleted");
        setState(() {
          _data1howItemWhenCovered = false;
          _data1WillAcceptIndex = -1;
          startData1Index = -1;
          _data2howItemWhenCovered = false;
          _data2WillAcceptIndex = -1;
          startData2Index = -1;
        });
      },
      //用戶拖動(dòng)item時(shí),那個(gè)給用戶看起來(lái)被拖動(dòng)的widget,(就是會(huì)跟著用戶走的那個(gè)widget)
      feedback: Container(
          width: 80, height: 80, child: _itemWidget(_data1List[index])),
      //這個(gè)是當(dāng)item被拖動(dòng)時(shí),item原來(lái)位置用來(lái)占位的widget,(用戶把item拖走后原來(lái)的地方該顯示的就是這個(gè))
      childWhenDragging: Container(
        child: SizedBox(
          child:
              _data1howItemWhenCovered ? _itemWidget(_data1List[index]) : null,
        ),
      ),
    );
  }

  Widget _createImg2Widget(int index) {
    return LongPressDraggable(
      data: index,
      child: DragTarget<int>(
        //松手時(shí) 如果onWillAccept返回true 那么就會(huì)調(diào)用,本案例不使用。
        onAccept: (int data) {},
        //繪制widget
        builder: (context, data, rejects) {
          return _data2WillAcceptIndex >= 0 && _data2WillAcceptIndex == index
              ? null
              : _itemWidget(_data2List[index]);
        },
        //手指拖著一個(gè)widget從另一個(gè)widget頭上滑走時(shí)會(huì)調(diào)用
        onLeave: (data) {
          print('2===$data is Leaving item $index');
          if (startData1Index != -1) {
            startData1Index = -1;
            return;
          }
          _data2WillAcceptIndex = -1;
          setState(() {
            _data2howItemWhenCovered = false;
            _data2List = _data2ListBackup;
          });
        },
        //接下來(lái)松手 是否需要將數(shù)據(jù)給這個(gè)widget  因?yàn)樾枰谕蟿?dòng)時(shí)改變UI,所以在這里直接修改數(shù)據(jù)源
        onWillAccept: (int fromIndex) {
          print('2===$index will accept item $fromIndex');
          bool accept = false;
          if (fromIndex < _data2List.length && startData1Index == -1) {
            //本列表內(nèi)移動(dòng)
            if (_data2WillAcceptIndex != -1) {
              fromIndex = _data2WillAcceptIndex;
            }
            final accept = fromIndex != index;
            if (accept) {
              _data2WillAcceptIndex = index;
              _data2howItemWhenCovered = true;
              _data2List = _data2ListBackup;
              final fromData = _data2List[fromIndex];
              setState(() {
                _data2List.removeAt(fromIndex);
                _data2List.insert(index, fromData);
              });
            }
          } else {
            accept = true;
            //兩個(gè)列表間的移動(dòng)
            if (accept) {
              _data2WillAcceptIndex = index;
              _data2howItemWhenCovered = true;
              final fromData = _data1List[fromIndex];
              setState(() {
                _data1List.removeAt(fromIndex);
                _data2List.insert(index, fromData);
              });
            }
          }
          _data1ListBackup = _data1List;
          _data2ListBackup = _data2List;
          return accept;
        },
      ),
      onDragStarted: () {
        //開始拖動(dòng),備份數(shù)據(jù)源
        _data1ListBackup = _data1List;
        _data2ListBackup = _data2List;
        startData2Index = index;
        print('2===item $index ---------------------------onDragStarted');
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        print(
            '2===item $index ---------------------------onDraggableCanceled,velocity = $velocity,offset = $offset');
        //拖動(dòng)取消,還原數(shù)據(jù)源
        setState(() {
          _data1WillAcceptIndex = -1;
          _data1howItemWhenCovered = false;
          _data1List = _data1ListBackup;
          startData1Index = -1;
          _data2WillAcceptIndex = -1;
          _data2howItemWhenCovered = false;
          _data2List = _data2ListBackup;
        });
      },
      onDragCompleted: () {
        //拖動(dòng)完成,刷新狀態(tài),重置willAcceptIndex
        print("2===item $index ---------------------------onDragCompleted");
        setState(() {
          _data1howItemWhenCovered = false;
          _data1WillAcceptIndex = -1;
          startData1Index = -1;
          _data2howItemWhenCovered = false;
          _data2WillAcceptIndex = -1;
          startData2Index = -1;
        });
      },
      //用戶拖動(dòng)item時(shí),那個(gè)給用戶看起來(lái)被拖動(dòng)的widget,(就是會(huì)跟著用戶走的那個(gè)widget)
      feedback: Container(
          width: 80, height: 80, child: _itemWidget(_data2List[index])),
      //這個(gè)是當(dāng)item被拖動(dòng)時(shí),item原來(lái)位置用來(lái)占位的widget,(用戶把item拖走后原來(lái)的地方該顯示的就是這個(gè))
      childWhenDragging: Container(
        child: SizedBox(
          child:
              _data2howItemWhenCovered ? _itemWidget(_data2List[index]) : null,
        ),
      ),
    );
  }

  Widget _itemWidget(String data) {
    return Container(
      decoration: BoxDecoration(
        color: ColorUtils.parseColorString("#c9daf8"),
        borderRadius: BorderRadius.circular(10.0),
      ),
      child: Text(
        data,
        style: TextStyle(
            fontSize: 15,
            color: Colors.black,
            fontWeight: FontWeight.normal,
            decoration:
                TextDecoration.none), //, decoration: TextDecoration.none
      ),
    );
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容