SideBar是APP开发当中常见的功能之一,多用于索引列表,如城市选择,分类等。在优化OpenGit趋势列表时,因为在选择语言时须要用到这样的控件,尝试开发了这个控件,效果以下图所示git
完成SideBar须要向外提供如下参数github
选中letter的回掉函数以下所示canvas
typedef OnTouchingLetterChanged = void Function(String letter);
复制代码
索引列表数据以下面代码所示api
const List<String> A_Z_LIST = const [
"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",
"#"
];
复制代码
当按下SideBar时须要刷新UI,因此SideBar须要继承StatefulWidget
,构造函数以下所示ide
class SideBar extends StatefulWidget {
SideBar({
Key key,
@required this.onTouch,
this.width = 30,
this.letterHeight = 16,
this.color = Colors.transparent,
this.textStyle = const TextStyle(
fontSize: 12.0,
color: Color(YZColors.subTextColor),
),
this.touchDownColor = const Color(0x40E0E0E0),
this.touchDownTextStyle = const TextStyle(
fontSize: 12.0,
color: Color(YZColors.mainTextColor),
),
});
final int width;
final int letterHeight;
final Color color;
final Color touchDownColor;
final TextStyle textStyle;
final TextStyle touchDownTextStyle;
final OnTouchingLetterChanged onTouch;
}
复制代码
在_SideBarState
中,须要经过touch的状态来判断背景色的展现,相关代码以下所示函数
class _SideBarState extends State<SideBar> {
bool _isTouchDown = false;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
color: _isTouchDown ? widget.touchDownColor : widget.color,
width: widget.width.toDouble(),
child: _SlideItemBar(
letterWidth: widget.width,
letterHeight: widget.letterHeight,
textStyle: _isTouchDown ? widget.touchDownTextStyle : widget.textStyle,
onTouch: (letter) {
if (widget.onTouch != null) {
setState(() {
_isTouchDown = !TextUtil.isEmpty(letter);
});
widget.onTouch(letter);
}
},
),
);
}
}
复制代码
上面代码,主要部分经过_SlideItemBar
的letter状态的改变来刷新Container
的color,下面看下_SlideItemBar
的实现,相关代码以下所示优化
class _SlideItemBar extends StatefulWidget {
final int letterWidth;
final int letterHeight;
final TextStyle textStyle;
final OnTouchingLetterChanged onTouch;
_SlideItemBar(
{Key key,
@required this.onTouch,
this.letterWidth = 30,
this.letterHeight = 16,
this.textStyle})
: assert(onTouch != null),
super(key: key);
@override
_SlideItemBarState createState() {
return _SlideItemBarState();
}
}
复制代码
上文代码,没有作过多的操做,只是定义了几个变量,详细的操做在_SlideItemBarState
。 在_SlideItemBarState
中,须要知道每一个letter
在垂直方向上的偏移高度,以下面代码所示动画
void _init() {
_letterPositionList.clear();
_letterPositionList.add(0);
int tempHeight = 0;
A_Z_LIST?.forEach((value) {
tempHeight = tempHeight + widget.letterHeight;
_letterPositionList.add(tempHeight);
});
}
复制代码
填充每一个letter widget,并设置固定宽高,代码以下所示ui
List<Widget> children = List();
A_Z_LIST.forEach((v) {
children.add(SizedBox(
width: widget.letterWidth.toDouble(),
height: widget.letterHeight.toDouble(),
child: Text(v, textAlign: TextAlign.center, style: _style),
));
});
复制代码
在滑动SideBar
过程当中,须要检测手势事件,代码以下所示this
GestureDetector(
onVerticalDragDown: (DragDownDetails details) {
//计算索引列表距离顶部的距离
if (_widgetTop == -1) {
RenderBox box = context.findRenderObject();
Offset topLeftPosition = box.localToGlobal(Offset.zero);
_widgetTop = topLeftPosition.dy.toInt();
}
//获取touch点在索引列表的偏移值
int offset = details.globalPosition.dy.toInt() - _widgetTop;
int index = _getIndex(offset);
//判断索引是否在列表中,若是存在,则通知上层更新数据
if (index != -1) {
_lastIndex = index;
_triggerTouchEvent(A_Z_LIST[index]);
}
},
onVerticalDragUpdate: (DragUpdateDetails details) {
//获取touch点在索引列表的偏移值
int offset = details.globalPosition.dy.toInt() - _widgetTop;
int index = _getIndex(offset);
//而且先后两次的是否一致,若是不一致,则通知上层更新数据
if (index != -1 && _lastIndex != index) {
_lastIndex = index;
_triggerTouchEvent(A_Z_LIST[index]);
}
},
onVerticalDragEnd: (DragEndDetails details) {
_lastIndex = -1;
_triggerTouchEvent('');
},
onTapUp: (TapUpDetails details) {
_lastIndex = -1;
_triggerTouchEvent('');
},
//填充UI
child: Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
)
复制代码
上文代码,在onVerticalDragDown
事件时,首次获取索引距离顶部的高度,并经过touch点的y坐标获取到touch点在偏移值,并经过该值找到目前touch的索引,记录该状态,并通知上层ui;在onVerticalDragUpdate
事件时,获取索引跟onVerticalDragDown
一致,只是多了出重的操做。而onVerticalDragEnd
和onTapUp
表明touch事件的结束。到此,能够获取到触摸SideBar时,回掉的letter
数据。
SideBar
一般展现在ListView
的上面,父容器咱们采用Stack
,以下面代码所示
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
body: Stack(
children: <Widget>[
_buildSideBar(context),
_buildLetterTips(),
],
),
);
}
Widget _buildSideBar(BuildContext context) {
return Offstage(
offstage: widget.offsetBuilder == null,
child: Align(
alignment: Alignment.centerRight,
child: SideBar(
onTouch: (letter) {
setState(() {
_letter = letter;
});
},
),
),
);
}
Widget _buildLetterTips() {
return Offstage(
offstage: TextUtil.isEmpty(_letter),
child: Align(
alignment: Alignment.center,
child: Container(
alignment: Alignment.center,
width: 65.0,
height: 65.0,
color: Color(0x40000000),
child: Text(
TextUtil.isEmpty(_letter) ? '' : _letter,
style: YZConstant.largeLargeTextWhite,
),
),
),
);
}
复制代码
当接收到letter
发生改变时,会经过setState
刷新ui,当_letter
不为空时,就会展现当前letter的提示。
滚动ListView目前只发现两种方法,以下面代码所示
//带动画的滚动
scrollController.animateTo(double offset);
//不带动画的滚动
scrollController.jumpTo(double offset);
复制代码
因为上述两种方法都须要知道滚动的具体位置,因此须要知道ListView列表的每一个item相对于屏幕顶部的偏移量,因此高度必须是固定的。
调用接口github-trending-api.now.sh/languages,并封装bean对象,以下面代码所示
List<TrendingLanguageBean> getTrendingLanguageBeanList(List<dynamic> list) {
List<TrendingLanguageBean> result = [];
list.forEach((item) {
result.add(TrendingLanguageBean.fromJson(item));
});
return result;
}
@JsonSerializable()
class TrendingLanguageBean extends Object {
@JsonKey(name: 'id')
String id;
@JsonKey(name: 'name')
String name;
String letter;
bool isShowLetter;
TrendingLanguageBean(this.id, this.name, {this.letter});
factory TrendingLanguageBean.fromJson(Map<String, dynamic> srcJson) =>
_$TrendingLanguageBeanFromJson(srcJson);
Map<String, dynamic> toJson() => _$TrendingLanguageBeanToJson(this);
}
复制代码
对获取到的数据进行排序,以下面代码所示
void _sortListByLetter(List<TrendingLanguageBean> list) {
if (list == null || list.isEmpty) return;
list.sort(
(a, b) {
if (a.letter == "@" || b.letter == "#") {
return -1;
} else if (a.letter == "#" || b.letter == "@") {
return 1;
} else {
return a.letter.compareTo(b.letter);
}
},
);
}
复制代码
经过语言对应的首字母,设置其展现状态,以下面代码所示
void _setShowLetter(List<TrendingLanguageBean> list) {
if (list != null && list.isNotEmpty) {
String tempLetter;
for (int i = 0, length = list.length; i < length; i++) {
TrendingLanguageBean bean = list[i];
String letter = bean.letter;
if (tempLetter != letter) {
tempLetter = letter;
bean.isShowLetter = true;
} else {
bean.isShowLetter = false;
}
}
}
}
复制代码
列表数据已经准备完毕,初始化单个item的高度,以下面代码所示
double getLetterHeight() => 48.0;
double getItemHeight() => 56.0;
复制代码
而后进一步计算每一个letter在ListView
中所处的高度,以下面代码所示
void _initListOffset(List<TrendingLanguageBean> list) {
_letterOffsetMap.clear();
double offset = 0;
String letter;
list?.forEach((v) {
if (letter != v.letter) {
letter = v.letter;
_letterOffsetMap.putIfAbsent(letter, () => offset);
offset = offset + getLetterHeight() + getItemHeight();
} else {
offset = offset + getItemHeight();
}
});
}
复制代码
经过letter
获取滚动的指定高度,以下面代码所示
double getOffset(String letter) => _letterOffsetMap[letter];
复制代码
当获取到高度后,完成ListView
的滚动,以下面代码所示
if (offset != null) {
_scrollController.jumpTo(offset.clamp(
.0, _scrollController.position.maxScrollExtent));
}
复制代码
上文SideBar的封装,用SizeBox
封装每一个letter,而后存放在List<Widget>
列表中,最后填充Column
,以下面代码所示
List<Widget> children = List();
A_Z_LIST.forEach((v) {
children.add(SizedBox(
width: widget.letterWidth.toDouble(),
height: widget.letterHeight.toDouble(),
child: Text(v, textAlign: TextAlign.center, style: _style),
));
});
child: Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
复制代码
下面用CustomPainter
实现SideBar,以下面代码所示
class _SideBarPainter extends CustomPainter {
final TextStyle textStyle;
final int width;
final int height;
TextPainter _textPainter;
_SideBarPainter(this.textStyle, this.width, this.height) {
_textPainter = new TextPainter(
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
);
}
@override
void paint(Canvas canvas, Size size) {
int length = A_Z_LIST.length;
for (int i = 0; i < length; i++) {
_textPainter.text = new TextSpan(
text: A_Z_LIST[i],
style: textStyle,
);
_textPainter.layout();
_textPainter.paint(
canvas, Offset(width.toDouble() / 2, i * height.toDouble()));
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
复制代码
使用_SideBarPainter
以下面代码所示
child: CustomPaint(
painter: _SideBarPainter(
widget.textStyle, widget.width, widget.letterHeight),
size: Size(widget.width.toDouble(), _height),
),
复制代码