请确保您没有在下面示例中的小部件内声明selectedValue,以下示例完全适用于我。
![输入图像描述](https://istack.dev59.com/hLUzu.gif)
在dartpad上查看工作代码以进行测试。
var currentSelectedValue;
const deviceTypes = ["Mac", "Windows", "Mobile"];
Widget typeFieldWidget() {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
hint: Text("Select Device"),
value: currentSelectedValue,
isDense: true,
onChanged: (newValue) {
setState(() {
currentSelectedValue = newValue;
});
print(currentSelectedValue);
},
items: deviceTypes.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
},
),
);
}
替代解决方案
如果您正在使用无状态小部件中的DropDownButton,您可以通过将其包装在ValueListenableBuilder中来重新构建dropDown Widget。
class MyWidget extends StatelessWidget {
String? currentSelectedValue;
final ValueNotifier<List<String>> _listNotifier =
ValueNotifier<List<String>>(["Mac", "Windows", "Mobile"]);
Widget typeFieldWidget() {
return ValueListenableBuilder(
valueListenable: _listNotifier,
builder: (BuildContext context, List<String> list, Widget? child) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 20),
child: FormField<String>(
builder: (FormFieldState<String> state) {
return InputDecorator(
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0))),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
hint: Text("Select Device"),
value: currentSelectedValue,
isDense: true,
onChanged: (newValue) {
currentSelectedValue = newValue;
_listNotifier.notifyListeners();
},
items: list.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
},
),
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: typeFieldWidget(),
));
}
}