ListView 的使用
记录一下我使用ListView的经历。刚开始接触Flutter的时候,我避开了这种一看就更加复杂的东西,先去使用了Text,Icon,但做的项目需要达到的动态加载相似item,看看是避不开了。
1. 第一种使用方式
这种方式算是我自己研究出来的用法,刚开始有个页面,只要动态加载相似条目,然后每个条目里有个按钮会触发回调就行,我看了listview里有个children,那好办,我就提供了个List
Container(
width: 1000,
height: 500,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 2),
),
child: ListView(
children: refreshListWidget(),
),
),
//这边生成列表,连的myListItem,是自己写的StatefulWidget,带一个回调
List<Widget> refreshListByValueList(List<Value> value) {
List<Widget> tempList = [];
int index = 0;
String name = "";
for (var i = 0; i < value.length; i++) {
setState(() {
index = i;
name = value[i].name;
});
print('refreshListWidget: ${index},${name}');
tempList.add(myListItem(
i,
name,
ItemCallback: refreshListWidget,
));
}
return tempList;
}
2. 第二种使用方式
如果写的程序,上面这种方式够用的话,也就不回来研究这种方式了,这次是因为要研究Listview单选效果,使用上面的方式,没有办法通知其他item改成不选中状态,查了点资料,使用了Listview.Builder来做的。
Container(
width: 1000,
height: 500,
decoration: BoxDecoration(
border: Border.all(color: Colors.blue, width: 2),
),
child: refreshListWidget(),
),
),
//同样放在refreshListWidget里了, listData的定义和赋值就不放进来了
Widget refreshListWidget() {
print('refreshListWidget now');
return ListView.builder(
itemCount: listData.length,
itemBuilder: (BuildContext context, int index) {
var item = listData[index];
return ListTile(
title: Text(item.listItem.name, ),
selected: item.isSelected,
selectedTileColor: Colors.lightBlueAccent[100],
selectedColor: Colors.black,
onTap: () {
setState(() {
for (var i = 0; i < listData.length; i++) {
if (i == index) {
listData[i].isSelected = !listData[i].isSelected;
} else {
listData[i].isSelected = false;
}
}
});
},
);
});
}