flutter 实现左侧菜单(仿淘宝-商品分类 点击滚动到指定位置)

实现代码如下

double itemHeight=40.0;

Widget  left=ListView.builder(

        shrinkWrap:true,

        itemExtent:itemHeight,//确定每一个item的高度 会让item加载更加高效

        controller: _scrollController,

        itemCount: widget.data==null?0:widget.data.length,

        itemBuilder: (context,index){

          Widget list=InkWell(

            child:Container(

              width: 83.0,

              height: itemHeight,

              child: Center(

                child: Text(widget.data[index].name,

                    overflow: TextOverflow.ellipsis,

                    style: TextStyle(fontSize: 16.0),

                  ),

                ),

            ),

            onTap: (){

                setState(() {

                  activeIndex=index; 

                });

               ///屏幕高度减AppBar高度和底部高度

               double mediaHeight=(MediaQuery.of(context).size.height)-75.0-50.0;

               ///Item总数

               int itemCount=widget.data.length;

               ///滚动高度

               double scrollHeight=itemCount*itemHeight;

               ///公式如下:当前点击的Item/Item总数*滚动高度-屏幕高度/2+Item的高度/2

               double _top=activeIndex/itemCount*scrollHeight-mediaHeight/2+itemHeight/2;

              //  print("Top值:$_top 当前Item$activeIndex Item总数$itemCount 滚动条高度:$scrollHeight 屏幕高度$mediaHeight Item的高度:$itemHeight");

              _scrollController.animateTo(_top,duration: Duration(milliseconds: 300,),curve: Curves.fastOutSlowIn);

              widget.onSelected(widget.data[index].children);

            },

          );

          list=Row(

            crossAxisAlignment: CrossAxisAlignment.center,

            children: [

              Container(

                decoration: BoxDecoration(color: activeIndex==index? AppTheme.color_red:AppTheme.backageColor),

                height: 30.0,

                width: 3.0,

                ),

                Material(type: MaterialType.transparency,child: list)

            ],

          );

          return list;

        },

      );

你可能感兴趣的:(flutter 实现左侧菜单(仿淘宝-商品分类 点击滚动到指定位置))