美文网首页
flutter 仿微信索引列表

flutter 仿微信索引列表

作者: 心旷则神怡 | 来源:发表于2024-05-12 15:30 被阅读0次
演示demo.gif

拖动索引后,列表滑动判断有点问题,懒得优化了
触感反馈也没做,这玩意没意思,懒得加
用到了拼音获取首字母的库

pinyin: ^3.2.0
1.定义索引的数组和列表数组
List<String> words = [];//索引的数组
 List scoreList = []; //列表数组
2.处理索引的字母
//后台返回的列表数组
for (var scoreItem in state.scoreItems) {
      //取出第一个字
      var firstCharacter = '';
      if (scoreItem.isTop) {
        //置顶,置顶的时候显示的是圆圈,character是自定义的
        scoreItem.character = '○';
      }else if (RegExp(r"[a-zA-Z]").hasMatch(firstCharacter)) {
        //正则判断-是英文
        scoreItem.character = firstCharacter.toUpperCase();
      } else if (RegExp(r"[\u4e00-\u9fa5]") .hasMatch(firstCharacter)) {
        //正则判断-是汉字
        final pinyin = PinyinHelper.getShortPinyin(firstCharacter);
        //汉字的时候,取出拼音首字母,转大写
        scoreItem.character = pinyin.toUpperCase();
      } else {
        //不是英文或汉字的时候,显示#
        scoreItem.character = '#';
      }
    }

//将列表数据根据索引排序,圆圈放在第一个,#放在最后一个,写的有点累赘,也懒得优化了
state.scoreItems.sort((ScoreItem a, ScoreItem b) {
      if(a.character == '#' || b.character=="#"){
        return a.character =='#'?1:-1;
      }
      if(a.character == '○' || b.character=="○"){
        return a.character == '○' ? -1:1;
      }
      return a.character!.compareTo(b.character!);
    });

    final tempWords = <String>[];
     for (var item in state.scoreItems) {
       tempWords.add('${item.character}');
     }
    //去重,得到需要的索引字母列表
    words = tempWords.toSet().toList();
    words .sort(( a,  b) {
       if(a == '#' || b=="#"){
         return a =='#'?1:-1;
       }
       if(a == '○' || b=="○"){
         return a == '○' ? -1:1;
       }
       return a.compareTo(b);
     });

//计算偏移量
Map<String, dynamic> groupedData = {};
    for (var item in state.scoreItems) {
      String character = item.character ?? '';
      if (groupedData[character] == null) {
        groupedData[character] = {
          'character': character,
          'offsetY': 0,
          'v': {'arr': []}
        };
      }
      groupedData[character]['v']['arr'].add(item);
    }
    // 转换为列表形式的结果
    List result = groupedData.values.toList();
    var offSetY = 0.0;
    for (var element in result) {
      element['offsetY'] = offSetY;
      List items = element['v']['arr'];
      for (ScoreItem item in items) {
        offSetY += 60;
      }
      offSetY += (10 + 30);
    }
3.搭建UI
Widget buildAZ() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      child: ListView.builder(
          controller: state.scrollController,
          itemCount: state.scoreList.length,
          itemBuilder: (cxt, section) {
            final List items = (state.scoreList[section]['v']['arr']);
            final random = Random().nextInt(8);
            return Container(
              margin: EdgeInsets.only(bottom: 30),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: EdgeInsets.only(bottom: 10),
                    child: Text(
                      state.scoreList[section]['character'] == '○'
                          ? 'Top'
                          : '${state.scoreList[section]['character']}',
                      style: TextStyle(fontSize: 14, color: AppColor.col232425),
                    ),
                  ),
                  Container(
                    clipBehavior: Clip.hardEdge,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      color: Colors.white,
                    ),
                    child: SlidableAutoCloseBehavior(
                      child: ListView.separated(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        itemBuilder: (cxt, row) {
                          ScoreItem item = items[row];
                          return GestureDetector(
                            onTap: () {
                              // do something here
                            },
                            child: Slidable(
                              key: Key('${item.id}'),
                              endActionPane: ActionPane(
                                  extentRatio: 0.6,
                                  motion: const BehindMotion(),
                                  children: [
                                    Expanded(
                                      child: GestureDetector(
                                        onTapUp: (details) {
                                          //PDF
                                        },
                                        child: Container(
                                          color: AppColor.col17DCEF,
                                          child: Center(
                                              child: Image.asset(
                                            'assets/shelf/shelf_icon_list_pdf.png',
                                            width: 24,
                                          )),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () {
                                          logic.toScoreInfo(id: item.id);
                                        },
                                        child: Container(
                                          color: AppColor.col199AF0,
                                          child: Center(
                                              child: Image.asset(
                                            'assets/shelf/shelf_icon_list_inf.png',
                                            width: 24,
                                          )),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () {
                                          //置顶
                                          // 改个参数,刷新界面就行了
                                        },
                                        child: Container(
                                          color: AppColor.colFFC717,
                                          // width: 48.w,
                                          child: Center(
                                              child: Image.asset(
                                            (item.isTop ?? false)
                                                ? 'assets/shelf/shelf_icon_list_untop.png'
                                                : 'assets/shelf/shelf_icon_list_top.png',
                                            width: 24,
                                          )),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTapUp: (details) {
                                          //分享
                                        },
                                        child: Container(
                                          color: AppColor.colFF7F26,
                                          // width: 48.w,
                                          child: Center(
                                              child: Image.asset(
                                            'assets/shelf/shelf_icon_list_share.png',
                                            width: 24,
                                          )),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: GestureDetector(
                                        onTap: () {
                                          //删除
                                        },
                                        child: Container(
                                          color: AppColor.colFD4246,
                                          child: Center(
                                              child: Image.asset(
                                            'assets/shelf/shelf_icon_list_del.png',
                                            width: 24,
                                          )),
                                        ),
                                      ),
                                    ),
                                  ]),
                              child: SizedBox(
                                height: 60,
                                child: Row(
                                  children: [
                                    Container(
                                      width: 28,
                                      height: 28,
                                      margin:
                                          EdgeInsets.only(left: 12, right: 12),
                                      decoration: BoxDecoration(
                                          color: state
                                              .colors[(random + row) % 8]
                                              .withOpacity(0.3),
                                          borderRadius:
                                              BorderRadius.circular(14)),
                                      child: Image.asset(
                                          'assets/shelf/com_icon_score.png'),
                                    ),
                                    Expanded(
                                      child: Text(
                                        '${item.name}',
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(
                                            color: AppColor.col232425,
                                            fontSize: 16),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                        itemCount: items.length,
                        separatorBuilder: (BuildContext context, int index) {
                          return Container(
                            height: 1,
                            color: AppColor.colF2F6F9,
                            margin: EdgeInsets.only(left: 52),
                          );
                        },
                      ),
                    ),
                  )
                ],
              ),
            );
          }),
    );
  }
4.事件处理
//获取选中的item的字符
  int getIndex({required BuildContext context, required Offset globalPosition}) {
    RenderBox box = context.findRenderObject() as RenderBox;
    double dy = box.globalToLocal(globalPosition).dy;
    const itemHeight =20;
    final index = (dy ~/ itemHeight).clamp(0, state.words.length - 1);
    return index;
  }
//手指在索引条上滑动的时候,改变显示的文字
void wordChanged(int index) {
    state.slipIndex = index;
    //进度条总高度
    final totalHeight = 20 * state.words.length/2;

    //当前的高度
    final currentHeight = 20 * index;

    final rate = currentHeight/totalHeight;
    state.indicatorOffsetY = currentHeight.toDouble()-15;

    // print(state.indicatorOffsetY);
    final word = state.words[index];
    final wordIndex =
        state.scoreList.indexWhere((element) => element['character'] == word);

    final currentOffsetY = state.scrollController.offset;
    double maxScrollExtent = state.scrollController.position.maxScrollExtent;
//判断的有问题,在滑动到所以列表的最后几个字母时,滚动偏移量不应该大于手机高度+组头的偏移量(好像是这个意思)
    if (wordIndex != -1) {
      final offsetY = state.scoreList[wordIndex]['offsetY'];
      if (currentOffsetY == maxScrollExtent && offsetY > maxScrollExtent) {
      } else {
        state.scrollController.animateTo(offsetY,
            duration: const Duration(milliseconds: 300), curve: Curves.easeIn);
      }
    }
    update(['indexSlip']);
  }

我真是一个很懒的人,其实很多细节没写,有问题留言吧!

相关文章

网友评论

      本文标题:flutter 仿微信索引列表

      本文链接:https://www.haomeiwen.com/subject/gzjufjtx.html