likes
comments
collection
share

Flutter学习-16- 微信项目学习-通讯录页面的索引条

作者站长头像
站长
· 阅读数 40
  • 主要实现右边的索引条和点击效果

Flutter学习-16- 微信项目学习-通讯录页面的索引条

1. 显示索引条

我们使用stack作为整个空间,右边的索引条和listView是叠放的,listView在下面所先显示。索引条是在右边固定的位置所以我们使用Positioned进行展示

child:Stack(
  children: [
    ListView.builder(itemBuilder: _itemBuilder,
      itemCount: _headerData.length+_listDatas.length,

    ),
    Positioned(
        top: 0.0,
        bottom: 0.0,
        right: 0.0,
        width: 30,
        child: Container(
          color: Color.fromRGBO(1, 1, 1, 0.3),
        )),
  ],
)

效果:

Flutter学习-16- 微信项目学习-通讯录页面的索引条

我们定义数据

const INDEX_WORDS = [
  '🔍',
  '☆',
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
];

我们定义一个数组words

final List<Widget> _words = [];

initState通过for循环遍历,我们使用Expanded进行拉伸


for(int i = 0 ;i<INDEX_WORDS.length;i++){

  _words.add(Expanded(child: Text(INDEX_WORDS[i],style: TextStyle(fontSize: 10,color: Colors.grey),)));

}

之前定位的位置去除颜色,之后使用column进行包裹

Positioned(
    top: 0.0,
    bottom: 0.0,
    right: 0.0,
    width: 30,
    child: Container(

      child:
      Column(
        children: _words
        ,
      ),
    )),

Flutter学习-16- 微信项目学习-通讯录页面的索引条

我们计算下这个位置,整体是居中显示,距离顶部是1/8,高度是屏幕的一半,底部不用。我们使用之前的宏定义,

top: screenHeight(context)/8,
height: screenHeight(context) / 2,
right: 0.0,
width: 30,

Flutter学习-16- 微信项目学习-通讯录页面的索引条

当然我们也可以使用listview进行作为索引条进行包裹

class _IndexBarState extends State<IndexBar> {
  Widget _item (BuildContext context,int index){
    return Container(
      alignment: Alignment.center,
      height: 15,
      child:
      Expanded(
        child:
        Text(INDEX_WORDS[index],style: TextStyle(fontSize: 10,color: Colors.grey),),
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child:ListView.builder(itemBuilder: _item,itemCount: INDEX_WORDS.length,),
    );
  }
}

效果类似: Flutter学习-16- 微信项目学习-通讯录页面的索引条

2. 索引条选中颜色

我们选中索引条的时候会有一个背景色,以及选中的时候索引为白色.我们定义2种颜色

Color _backgroundColor = Color.fromRGBO(1, 1, 1, 0);
Color _textColor = Colors.black;

我们修改下颜色

Flutter学习-16- 微信项目学习-通讯录页面的索引条

这里有拖拽的效果,所以整体添加一个手势我们使用竖直方向的手势

Flutter学习-16- 微信项目学习-通讯录页面的索引条

首先进来后就要切换背景颜色和文字颜色

//点击
onVerticalDragDown: (DragDownDetails details){
  setState(() {
    _backgroundColor = Color.fromRGBO(1, 1, 1, 0.5);
    _textColor = Colors.white;
  });

},
//离开
onVerticalDragEnd:(DragEndDetails details){
  setState(() {
    _backgroundColor = Color.fromRGBO(1, 1, 1, 0);
    _textColor = Colors.black;
  });

},

Flutter学习-16- 微信项目学习-通讯录页面的索引条 但是文字颜色没有改变,是因为words创建没有放在build里面,是放在initState中,initState相当于我们的viewDidLoad类似 ,增量渲染都是在build中,因此我们在flutter中关于组件的创建都要放在build中。 修改后效果如下:

Flutter学习-16- 微信项目学习-通讯录页面的索引条

下一篇介绍选中的气泡样式以及和列表的联动。

转载自:https://juejin.cn/post/7030376088899436552
评论
请登录