在我定义下拉按钮的 StatefulWidget 类 Customdropdownbutton 下面
class Customdropdownbutton extends StatefulWidget {
Customdropdownbutton({@required this.defaultValue, @required this.listValue, this.enable});
String defaultValue;
List<String> listValue;
bool enable;
@override
_CustomdropdownbuttonState createState() => _CustomdropdownbuttonState();
}
class _CustomdropdownbuttonState extends State<Customdropdownbutton> {
@override
Widget build(BuildContext context) {
String _valore;
return DropdownButton<String>(
value: widget.defaultValue.isEmpty ? widget.listValue[0] : _valore,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: widget.enable ? (String newValue) {
setState(() {
_valore = newValue;
});
} : null,
items: widget.listValue.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}
下面我尝试实例化类 Customdropdownbutton,在 UI 中我看到下拉按钮但我无法更改值(所选文本始终是 widget.listValue[0])
class MyMain extends StatefulWidget {
@override
Widget build(BuildContext context) {
final auth = Provider.of<AuthBase>(context, listen: false);
final String emailMy = auth.currentUser.email;
return scaffold(
.....
body: _buildFormChildren(emailMy),
}
List<Widget> _buildFormChildren(String emailMy) {
List<String> listValue = ['1a', '2b'];
String defaultValue = '1a';
bool enable = true;
return [
**Customdropdownbutton(defaultValue: '', listValue : listValue, enable: true, ),**
],
....
}
}
答案 0 :(得分:0)
在 build
的 _CustomdropdownbuttonState
方法中,您检查 widget.defaultValue
是否为空(由于您没有更改它,因此始终为空)并计算 widget.listValue[0]
。即使您更改 _valore
,条件也会继续检查 widget.defaultValue
是否为空。您可以执行以下操作:
class _CustomdropdownbuttonState extends State<Customdropdownbutton> {
// Use _valore as a property instead of a local variable
String _valore;
@override
void initState() {
super.initState();
// Use _valore to store the default value
_valore = widget.defaultValue;
}
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
// Check _valore instead of widget.defaultValue
value: _valore.isEmpty ? widget.listValue[0] : _valore,
icon: const Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: const TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: widget.enable ? (String newValue) {
setState(() {
_valore = newValue;
});
} : null,
items: widget.listValue.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
}
}