所以我想构建一个带有复选框的列表视图,并且数据应该是使用模型动态的。如有任何帮助,我们将不胜感激。
您可以像这样使用StatefulWidget
、FutureBuilder
、ListView.builder
和CheckboxListTile
。
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
List<String> listOfItems;
List<bool> itemCheckedState = [];
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: fetchListOfItems(),
builder: (context, snapshot){
if(!snapshot.hasData){
return const CircularProgressIndicator();
}
else {
listOfItems = snapshot.data;
for(int i = 0; i < listOfItems.length; i++){
itemCheckedState.add(false);
}
return ListView.builder(
itemCount: listOfItems.length,
itemBuilder: (context, index){
return CheckboxListTile(
title: Text(listOfItems[index]),
value: itemCheckedState[index],
onChanged: (newValue){
setState((){
itemCheckedState[index] = newValue;
});
},
);
}
);
}
}
);
}
Future<List<String>> fetchListOfItems() async {
//for demo purpose lets just return a list after 2 seconds
//here you can code for fetching your dynamic data instead
List<String> list = ['abc', 'def', 'xyz'];
await Future.delayed(Duration(seconds: 2), (){});
return list;
}
}