Скорее всего, вам следует использовать StatefulWidget
и метод setState
.
Пример:
var _formKey = GlobalKey<FormState>();
String _dropdownError;
String _selectedItem;
_validateForm() {
bool _isValid = _formKey.currentState.validate();
if (_selectedItem == null) {
setState(() => _dropdownError = "Please select an option!");
_isValid = false;
}
if (_isValid) {
//form is valid
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: ListView(children: <Widget>[
TextFormField(validator: (val) {
if (val.isEmpty) return "This field is required";
return null;
}
//other textformfield properties
),
DropdownButtonHideUnderline(
child: DropdownButton<String>(
value: _selectedItem,
isExpanded: true,
hint: Text("Select option", maxLines: 1),
items: ["Option 1", "Option 2", "Option 3"].map((String value) {
return DropdownMenuItem<String>(
value: value,
child: new Text(
value ?? "",
textAlign: TextAlign.left,
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: true,
),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedItem = value;
_dropdownError = null;
});
},
),
),
_dropdownError == null
? SizedBox.shrink()
: Text(
_dropdownError ?? "",
style: TextStyle(color: Colors.red),
),
RaisedButton(
onPressed: () => _validateForm(),
child: Text("Submit"),
),
]));
}