flutter 仿微信索引列表

演示demo.gif

拖動(dòng)索引后誓焦,列表滑動(dòng)判斷有點(diǎn)問(wèn)題
用到了拼音獲取首字母的庫(kù)

pinyin: ^3.2.0
1.定義索引的數(shù)組和列表數(shù)組
List<String> words = [];//索引的數(shù)組
 List scoreList = []; //列表數(shù)組
2.處理索引的字母
//后臺(tái)返回的列表數(shù)組
for (var scoreItem in state.scoreItems) {
      //取出第一個(gè)字
      var firstCharacter = '';
      if (scoreItem.isTop) {
        //置頂,置頂?shù)臅r(shí)候顯示的是圓圈,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);
        //漢字的時(shí)候着帽,取出拼音首字母杂伟,轉(zhuǎn)大寫
        scoreItem.character = pinyin.toUpperCase();
      } else {
        //不是英文或漢字的時(shí)候,顯示#
        scoreItem.character = '#';
      }
    }

//將列表數(shù)據(jù)根據(jù)索引排序仍翰,圓圈放在第一個(gè)赫粥,#放在最后一個(gè),寫的有點(diǎn)累贅歉备,也懶得優(yōu)化了
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);
     });

//計(jì)算偏移量
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);
    }
    // 轉(zhuǎn)換為列表形式的結(jié)果
    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: () {
                                          //置頂
                                          // 改個(gè)參數(shù)傅是,刷新界面就行了
                                        },
                                        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;
  }
//手指在索引條上滑動(dòng)的時(shí)候,改變顯示的文字
void wordChanged(int index) {
    state.slipIndex = index;
    //進(jìn)度條總高度
    final totalHeight = 20 * state.words.length/2;

    //當(dāng)前的高度
    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;
//判斷的有問(wèn)題,在滑動(dòng)到所以列表的最后幾個(gè)字母時(shí)喧笔,滾動(dòng)偏移量不應(yīng)該大于手機(jī)高度+組頭的偏移量(好像是這個(gè)意思)
    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']);
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末帽驯,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子书闸,更是在濱河造成了極大的恐慌尼变,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件浆劲,死亡現(xiàn)場(chǎng)離奇詭異嫌术,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)牌借,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門度气,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人膨报,你說(shuō)我怎么就攤上這事磷籍。” “怎么了现柠?”我有些...
    開(kāi)封第一講書人閱讀 162,632評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵院领,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我够吩,道長(zhǎng)比然,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,180評(píng)論 1 292
  • 正文 為了忘掉前任周循,我火速辦了婚禮强法,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘湾笛。我一直安慰自己拟烫,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布迄本。 她就那樣靜靜地躺著硕淑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪嘉赎。 梳的紋絲不亂的頭發(fā)上置媳,一...
    開(kāi)封第一講書人閱讀 51,165評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音公条,去河邊找鬼拇囊。 笑死,一個(gè)胖子當(dāng)著我的面吹牛靶橱,可吹牛的內(nèi)容都是我干的寥袭。 我是一名探鬼主播路捧,決...
    沈念sama閱讀 40,052評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼传黄!你這毒婦竟也來(lái)了杰扫?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 38,910評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤膘掰,失蹤者是張志新(化名)和其女友劉穎章姓,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體识埋,經(jīng)...
    沈念sama閱讀 45,324評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡凡伊,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了窒舟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片系忙。...
    茶點(diǎn)故事閱讀 39,711評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖惠豺,靈堂內(nèi)的尸體忽然破棺而出笨觅,到底是詐尸還是另有隱情,我是刑警寧澤耕腾,帶...
    沈念sama閱讀 35,424評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站杀糯,受9級(jí)特大地震影響扫俺,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜固翰,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評(píng)論 3 326
  • 文/蒙蒙 一狼纬、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧骂际,春花似錦疗琉、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,668評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至太示,卻和暖如春柠贤,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背类缤。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,823評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工臼勉, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人餐弱。 一個(gè)月前我還...
    沈念sama閱讀 47,722評(píng)論 2 368
  • 正文 我出身青樓宴霸,卻偏偏與公主長(zhǎng)得像囱晴,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瓢谢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容