我想使复选框动态地抖动,从数据库MySQL中检索数据。因此,这段代码可以显示来自MySQL的数据。但还是无法一一核对。这是我的代码:
class TambahDataTanaman extends StatefulWidget {
@override
_TambahDataTanamanState createState() => _TambahDataTanamanState();
}
class _TambahDataTanamanState extends State<TambahDataTanaman> {
GlobalKey<FormState> addTanamanKey = GlobalKey<FormState>();
bool selected = false;
Future<List> getData() async {
final response =
await http.get("http://192.168.1.9/tanampedia/tanahtampil.php");
return json.decode(response.body);
}
List selectedData = [];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Tambah Data Tanaman"),
backgroundColor: Colors.green,
),
body: SingleChildScrollView(
child: Form(
key: addTanamanKey,
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListView(
shrinkWrap: true,
children: [
new Column(
children: [
new FutureBuilder<dynamic>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
//List list = snapshot.data;
return CheckboxListTile(
title:
Text(snapshot.data[index]['nama']),
value: selected,
onChanged: (bool newSelected) {
setState(() {
selected = newSelected;
});
},
dense: true,
);
})
: new Center(
child: new CircularProgressIndicator());
}),
new RaisedButton(
child: new Text(
"Tambah Data",
style: TextStyle(color: Colors.white),
),
color: Colors.green,
onPressed: () {}),
],
),
],
),
),
),
));
}
}
我使用future builder为我的CheckBoxList创建列表。但是在运行代码的时候,上面代码的结果是同时检查了所有的值,那么如何使它们正确呢?
这是因为来自循环的项是相同的,所以您应该添加Key:Key(index),
return CheckboxListTile(
title: Text(snapshot.data[index]['nama']),
value: selected,
key: Key(index),
onChanged: (bool newSelected) {
setState(() {
selected = newSelected;
});
},
dense: true,
);