[英]Add onTap to CheckboxListTile to call AlertDialog
我正在构建一个Flutter移动应用程序来参加会议。
我正在使用CheckboxListTile显示注册列表。 单击或点击列表项时,我想调用“警报对话框”。 但是,我发现CheckboxListTile没有onTap属性。
那么有什么方法可以将onTap添加到CheckboxListTile吗? 谢谢!
我用于创建CheckboxListTile的代码的一部分:
Widget staffList(AsyncSnapshot<EnrollmentListModel> snapshot) {
if (snapshot.data.staffList.length > 0) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.staffList.length,
itemBuilder: (context, index) {
return Card(
child: CheckboxListTile(
title: Text(
'${snapshot.data.staffList[index].listName}',
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
value: snapshot.data.staffList[index].attendanceStatus == 'Y',
onChanged: (bool value) {},
activeColor: Colors.green,
),
);
},
);
}
else {
return Center(child: Text("No enrollment for this course."));
}
}
onTap
不起作用的原因是因为checkboxListTile
本身是可单击的,并且如果我们尝试再次在其上应用onTap
,它将与原始的click事件冲突。 因此,您可以在将值设置为单击后直接在onChanged
方法中传递打开alertDialog
的调用,而不是将您的checkboxListTile
包装在GestureDetector
。 下面的示例工作代码:
return Scaffold(
appBar: new AppBar(title: new Text('CheckboxListTile demo')),
body: ListView(
children: values.keys.map((String key) {
return CheckboxListTile(
title: Text(key),
value: values[key],
onChanged: (bool value) {
setState(() {
values[key] = value;
});
_showDialog();
},
);
}).toList(),
),
);
}
void _showDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Alert Dialog title"),
content: new Text("Alert Dialog body"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
});
输出是,如果您点击foo
复选框,它将选中该复选框并打开alertDialog。 希望这能回答您的问题。
您可以将CheckboxListTile
包装在GestureDetector
,该对象具有onTap
属性以及许多其他有用的属性。
有关GestureDetector
类的更多文档可以在这里找到。
范例-
Widget staffList(AsyncSnapshot<EnrollmentListModel> snapshot) {
if (snapshot.data.staffList.length > 0) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.staffList.length,
itemBuilder: (context, index) {
return Card(
child: GestureDetector(
onTap: () {
//Add code for showing AlertDialog here
},
child: CheckboxListTile(
title: Text(
'${snapshot.data.staffList[index].listName}',
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
value: snapshot.data.staffList[index].attendanceStatus == 'Y',
onChanged: (bool value) {},
activeColor: Colors.green,
),
),
);
},
);
}
else {
return Center(child: Text("No enrollment for this course."));
}
}
替代方法-如果只需要onTap
回调,则也可以使用InkWell
小部件。 只需将以上代码中的InkWell
替换为GestureDetector
InkWell
。
有关InkWell
文档可以在这里找到。
body: ListView.builder(
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
child: Text(index.toString()),
onTap: () {//Write your AlertDialog code here},
);
},
itemCount: 10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.