起因
最近在用flutter 開發(fā)一個(gè)web頁面婿崭,然后遇到界面需要用到iOS中的UISegmentedControl
就像這樣
image.png
Flutter中有CupertinoSegmentedControl
杉女,于是就直接用了伯顶。
我先在Flutter移動(dòng)端開發(fā)好了界面袱衷,一切顯示正常皿曲,就像這樣
image.png
沒啥問題媒佣。
但是當(dāng)我把組件遷移到web端時(shí)爷速,出了問題。
image.png
估計(jì)短時(shí)間內(nèi)也得不到解決啃洋,于是決定自己造個(gè)輪子传货。
先展示一下成果
image.png
優(yōu)化
原先CupertinoSegmentedControl
代碼冗余,數(shù)據(jù)處理相對麻煩宏娄。需要傳入一個(gè)Map<String, Widget>
類型的參數(shù)作為數(shù)據(jù)源问裕。
Widget segmentControll(
List titles, String groupValue, Function onValueChange) {
TextStyle style = TextStyle(fontSize: 14);
Color grey = Color.fromARGB(255, 101, 102, 103);
List<String> keys = ["a", "b", "c", "d"];
Map<String, Widget> children = {};
for (var i = 0; i < titles.length; i++) {
String str = keys[I];
Widget w = Container(
alignment: Alignment.center,
width: 56.0,
height: 32,
child: Text(
titles[I],
style: style,
));
// Map item = {str:w};
// children.add(item);
children[str] = w;
}
return CupertinoSegmentedControl(
onValueChanged: onValueChange,
pressedColor: Colors.white,
borderColor: grey,
selectedColor: grey,
groupValue: groupValue,
children: children);
}
我自己的輪子,只需要一個(gè)List<String>
即可孵坚,代碼量減少了許多
Widget segmentControll(List titles, String groupValue, Function onValueChange) {
Color grey = Color.fromARGB(255, 101, 102, 103);
return HBSegmentedControl(titleList: titles,selectedColor: grey,onTap: (index){
print(index);
});
}
集成
PUB 地址
https://pub.flutter-io.cn/packages/hbsegmented_control#-readme-tab-
在pubspec.yaml文件中添加這段代碼
dependencies:
hbsegmented_control: ^0.0.1