我是扑朔迷离的新手,我可以轻松创建无状态小部件,并在创建对象时要求设置值(@required this.value)
但是,我对于如何使用有状态的小部件有点迷茫。
当查看下面的代码时,我希望能够从创建的对象中获取“提示”值,并进入有状态的窗口小部件构造器,然后进入下拉菜单。我希望这是有道理的。
class MyDropdownButton extends StatefulWidget { MyDropdownButton({
this.hint, }); String hint; @override _MyDropdownButtonState createState() => _MyDropdownButtonState(); }
class _MyDropdownButtonState extends State<MyDropdownButton> { String dropdownValue; String hint;
@override Widget build(BuildContext context) {
return Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
'TO',
style: TextStyle(color: kColourGreyText),
),
DropdownButton<String>(
value: dropdownValue != null ? dropdownValue : null,
hint: Text(hint),
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: kColourGreyText),
underline: Container(
height: 2,
color: kColorPrimary,
),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items:
accountNameList.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
],
),
); } }
答案 0 :(得分:1)
您可以直接从状态访问窗口小部件属性。尝试widget.hint
答案 1 :(得分:1)
发现您的代码存在多个问题,
class MyDropdownButton extends StatefulWidget {
MyDropdownButton({@required this.hint}); // use @required for required parameters, like this one here
final String hint; // use final
@override
_MyDropdownButtonState createState() => _MyDropdownButtonState();
}
// below line you missed `<MyDropdownButton>` after `State`,
// I'd suggest using a recommended IDE with a recommended Flutter
// Extention to generate code samples
class _MyDropdownButtonState extends State<MyDropdownButton> {
String dropdownValue;
// I added below 3 lines to avoid the errors in this sample code
List<String> accountNameList = [];
Color kColorPrimary = Colors.blue;
Color kColourGreyText = Colors.grey;
@override
Widget build(BuildContext context) {
// You don't need `Expanded` here, just wrap it with `Row` only
return Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('TO', style: TextStyle(color: kColourGreyText)),
DropdownButton(
value: dropdownValue != null ? dropdownValue : null,
// when accessing parsed values in Statful,
// use widget.<variable name>
hint: Text(widget.hint),
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: kColourGreyText),
underline: Container(height: 2, color: kColorPrimary),
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: accountNameList.map((String value) {
return DropdownMenuItem(value: value, child: Text(value));
}).toList(),
),
],
);
}
}
再一次,我建议使用推荐的IDE和推荐的Flutter Extension来生成代码示例