Flutter仿照蘋果相冊(cè)長(zhǎng)按下拉滾動(dòng)多選中

最近朋友想讓我實(shí)現(xiàn)一個(gè)仿蘋果相冊(cè)長(zhǎng)按下拉選中的效果,奈何度娘不給力,找不到任何的有關(guān)文章,索性就自己來實(shí)現(xiàn)吧。希望以后有此需求的朋友能借鑒借鑒自己的文章,這樣也不枉自己花些筆墨為大家來介紹實(shí)現(xiàn)的思路和方法。

實(shí)現(xiàn)效果:(長(zhǎng)按下拉選中后續(xù)選項(xiàng))


2222.gif

首先,我們先來實(shí)現(xiàn)最基本的效果,單擊選中,再單擊,取消選中

import 'package:flutter/material.dart';

class AlbumDemo extends StatefulWidget {
  const AlbumDemo({Key? key}) : super(key: key);

  @override
  State<AlbumDemo> createState() => _AlbumDemoState();
}

class _AlbumDemoState extends State<AlbumDemo> {


  List selects = [];

  @override
  void initState() {
    super.initState();
    for(int i = 0; i < 400 ; i++){
      selects.add(0);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AlbumDemo'),),
      body: ListView.builder(itemBuilder: (BuildContext context,int index){
        return GestureDetector(
            onTap: (){
              selects[index] = ((selects[index]??0)==0)?1:0;
              setState(() {

              });
            },
            child: Container(
              color: Colors.white,
              child: Column(
                children: [
                  Container(
                      height: 80,
                      child: Row(
                        children: [
                          Icon( ((selects[index]??0) ==1)?Icons.check_box:Icons.check_box_outline_blank,),
                          SizedBox(width: 50,),
                          Text('$index'),
                        ],
                      )
                  ),
                  Container(
                    height: 0.5,
                    color: Colors.lightBlue,
                  )
                ],
              ),
            )
        );
      },itemCount: 400,),
    );
  }
}

接下來利用手勢(shì)來判別滑動(dòng)軌跡,并且為listview添加controller控制滑動(dòng)


import 'package:flutter/material.dart';

enum PullDirection {
  down,
  up,
}

class AlbumDemo extends StatefulWidget {
  const AlbumDemo({Key? key}) : super(key: key);

  @override
  State<AlbumDemo> createState() => _AlbumDemoState();
}

class _AlbumDemoState extends State<AlbumDemo> {

  List selects = [];//選中的暫存數(shù)組

  ScrollController _controller = ScrollController();

  double origin_offset = 0;//原始的標(biāo)記位置,用來判別是上拉還是下滑

  bool endDrap = false;//結(jié)束滑動(dòng)的標(biāo)志

  bool isPullingUp = false;//是否正在上滑中

  bool isPullingDown = false;//是否正在下滑中

  bool isAnimationing = false;//是否處于自動(dòng)滾動(dòng)中

  final GlobalKey _globalKey = GlobalKey();//用來獲取當(dāng)前的listview

  Offset saveOffset = Offset(0, 0);

  PullDirection direction = PullDirection.down;//滑動(dòng)方向

  @override
  void initState() {
    super.initState();
    for(int i = 0; i < 400 ; i++){
      selects.add(0);
    }
  }


  runloopScroll(bool down){

    print("isPullingDown = $isPullingDown");
    if(down){
      origin_offset+=80;
    }else{
      origin_offset-=80;
      if(origin_offset<0){
        origin_offset = 0;
      }
    }
    Future.delayed(Duration(milliseconds: 200),(){
      if(down){
        _controller.animateTo(origin_offset, duration: Duration(milliseconds: 200),curve:Curves.linear );
      }else{
        _controller.animateTo(origin_offset, duration: Duration(milliseconds: 200),curve:Curves.linear );
      }
    }).then((value){
      RenderBox box = _globalKey.currentContext?.findRenderObject() as RenderBox;
      var innerLocation =  box.globalToLocal(saveOffset);
      updateSelectionStatus(Offset(innerLocation.dx, innerLocation.dy+ (down?80:-80)),isSelected: direction==PullDirection.down);


      if(endDrap == true){
      }else{
        if(down){//下滑中
          if(isPullingDown) {
            runloopScroll(true);
          }
        }else{
          if(isPullingUp){
            runloopScroll(false);
          }
        }
      }

    });
  }


  updateSelectionStatus(Offset offset,{bool isSelected = true}){

    int index =   (_controller.offset.toInt() +   offset.dy.toInt()) ~/ 80 ;
    // print('滑動(dòng)經(jīng)過的index=$index');

    selects[index] = isSelected?1:0;
    setState(() {

    });


  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AlbumDemo'),),
      body: GestureDetector(
        onLongPress: (){
          print("長(zhǎng)按開始");
          endDrap = false;
          origin_offset = _controller.offset;
        },
        onLongPressEnd: (LongPressEndDetails details){
          print("長(zhǎng)按結(jié)束");
          endDrap = true;
          isAnimationing = false;
        },
        onLongPressMoveUpdate:(LongPressMoveUpdateDetails details){
          if(saveOffset.dy < details.globalPosition.dy){
            //下滑
            direction = PullDirection.down;
          }else{
            //上滑
            direction = PullDirection.up;
          }
          saveOffset = details.globalPosition;
          RenderBox box = _globalKey.currentContext?.findRenderObject() as RenderBox;
          var innerLocation =  box.globalToLocal(saveOffset);
          updateSelectionStatus(innerLocation,isSelected: direction==PullDirection.down);
          if(details.globalPosition.dy>=810){//下面的邊緣臨界點(diǎn),目前寫死(這里應(yīng)該是導(dǎo)航欄與定點(diǎn)的距離)
            if(isPullingUp){
              isPullingUp = false;
            }
            isPullingDown = true;
            if(isAnimationing){

            }else{
              runloopScroll(true);
              isAnimationing = true;
            }
          }else if(details.globalPosition.dy<=120){//上面的臨界點(diǎn),這里應(yīng)該是底部離定點(diǎn)的距離
            if(isPullingDown){
              isPullingDown = false;
              isAnimationing = false;
            }
            isPullingUp = true;
            if(isAnimationing){

            }else{
              runloopScroll(false);
              isAnimationing = true;
            }
          }else{
            if(isPullingDown){
              isPullingDown = false;
              isAnimationing = false;
            }
            if(isPullingUp){
              isPullingUp = false;
            }
          }
        },
        child: ListView.builder(key: _globalKey,controller: _controller,itemBuilder: (BuildContext context,int index){
          return GestureDetector(
              onTap: (){
                selects[index] = ((selects[index]??0)==0)?1:0;
                setState(() {

                });
              },
              child: Container(
                color: Colors.white,
                child: Column(
                  children: [
                    Container(
                        height: 80,
                        child: Row(
                          children: [
                            Icon( ((selects[index]??0) ==1)?Icons.check_box:Icons.check_box_outline_blank,),
                            SizedBox(width: 50,),
                            Text('$index'),
                          ],
                        )
                    ),
                    Container(
                      height: 0.5,
                      color: Colors.lightBlue,
                    )
                  ],
                ),
              )
          );
        },itemCount: 400,),
      )
    );
  }
}



大功告成、樓主省略了講解步驟,請(qǐng)見下回分解 哈哈

?著作權(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)容