当用户未在下拉菜单项上选择项时如何显示错误消息?



我试图从Flutter应用程序在firestore中收集数据。使用以下代码:我的问题是,当用户没有在DropdownMenuItem上选择项目时,如何显示错误消息?

body: Form(
key: _formKeyValue,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 12.0),
children: <Widget>[
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton(
items: _specialite
.map((value) => DropdownMenuItem(
child: Text(
value,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black),
),
value: value,
))
.toList(),
onChanged: (selectedAccountType) {
print('$selectedAccountType');
setState(() {
medicalType = selectedAccountType;
});
},
value: medicalType,
isExpanded: false,
hint: Text(
'choisissez la spécialité',
style: TextStyle(color: Colors.black),
),
)
],
),

....
....

我用了这个答案https://stackoverflow.com/a/59746301/15400156但屏幕上没有显示任何内容。

您可以将第一个菜单项设置为"选择xxx";,这也是默认项(索引0(,那么当用户点击"0"时,您可以检查索引;提交";按钮

您可以通过不同的方式实现这一点。从DropDownButton中删除value属性,并使用String medicalType;初始化medicalType。然后按下提交按钮,检查medicalType是否为空。以下是完整的代码。

class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
List<String> _specialite = ["abc", "def", 'ghi'];
String medicalType;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
//           key: _formKeyValue,
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 12.0),
children: <Widget>[
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
DropdownButton(
items: _specialite
.map((value) => DropdownMenuItem(
child: Text(
value,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
),
value: value,
))
.toList(),
onChanged: (String selectedAccountType) {
print('$selectedAccountType');
setState(() {
medicalType = selectedAccountType;
});
},
//                     value: medicalType,
isExpanded: false,
hint: Text(
'choisissez la spécialité',
style: TextStyle(color: Colors.black),
),
)
],
),
ElevatedButton(
onPressed: () {
if (medicalType == null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("please choose medical type")));
}
},
child: Text("submit"))
]),
));
}
}

最新更新