![](/img/trans.png)
[英]Flutter - DropdownButton onChanged does not call a function
[英]Flutter - DropdownButton onChanged returning null
我正在创建一个下拉列表,但是每当我单击一个值并尝试在 onChanged 部分打印它时,它都会打印 null,我做错了什么? 谢谢。 这是我的代码:
List<UserFontModel> _fonts = [
UserFontModel(fontFamily: 'Regular', fontWeight: FontWeight.w400),
UserFontModel(fontFamily: 'Bold', fontWeight: FontWeight.w700),
UserFontModel(fontFamily: 'Medium', fontWeight: FontWeight.w500),
UserFontModel(fontFamily: 'Light', fontWeight: FontWeight.w300),
UserFontModel(fontFamily: 'Thin', fontWeight: FontWeight.w100),
];
String _selectedFontStyle;
new DropdownButton<String>(
value: _selectedFontStyle,
hint: Text('Style'),
items: _fonts.map((fonts) => DropdownMenuItem<String> (
child: Container(
width: MediaQuery.of(context).size.width * 0.2,
child: Text(fonts.fontFamily, style: TextStyle(fontWeight: fonts.fontWeight),),
),
)).toList(),
onChanged: (String _) {
print(_);
},
),
当我选择一个项目时,我会看到:
flutter: null
有人可以帮忙吗?
请试试这个。
List<UserFontModel> _fonts = [
UserFontModel(fontFamily: 'Regular', fontWeight: FontWeight.w400),
UserFontModel(fontFamily: 'Bold', fontWeight: FontWeight.w700),
UserFontModel(fontFamily: 'Medium', fontWeight: FontWeight.w500),
UserFontModel(fontFamily: 'Light', fontWeight: FontWeight.w300),
UserFontModel(fontFamily: 'Thin', fontWeight: FontWeight.w100),
];
String _selectedFontStyle;
DropdownButton<String>(
hint: Text("Style"),
value: _selectedFontStyle,
onChanged: (String Value) {
setState(() {
_selectedFontStyle = Value;
});
},
items: _fonts.map((fonts) {
return DropdownMenuItem<String>(
value: fonts.fontFamily,
child: new Container(
width: MediaQuery.of(context).size.width * 0.2,
child: Text(fonts.fontFamily, style: TextStyle(fontWeight: fonts.fontWeight),),
)
);
}).toList(),
),
DropdownMenuItem 返回它的值字段。 所以你需要为孩子增加价值。
像这样尝试。
new DropdownButton<String>(
value: _selectedFontStyle,
hint: Text('Style'),
items: _fonts.map((fonts) => DropdownMenuItem<String> (
child: Container(
width: MediaQuery.of(context).size.width * 0.2,
child: Text(fonts.fontFamily, style: TextStyle(fontWeight: fonts.fontWeight),),
),
value: fonts.fontFamily, // add this line
)).toList(),
onChanged: (String _) {
print(_);
},
),
这对我有用:
new DropdownButton<UserFontModel>(
value: _fonts[0],
hint: Text('Style'),
items: _fonts
.map<DropdownMenuItem<UserFontModel>>((UserFontModel font) {
return DropdownMenuItem<UserFontModel>(
value: font,
child: Text(
font.fontFamily,
style: TextStyle(fontWeight: font.fontWeight),
),
);
}).toList(),
onChanged: (UserFontModel _) {
print(_.fontFamily);
},
),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.