当我试图使用文本小部件呈现item时,我收到了一个错误,说明它是未定义的。
当按下按钮时,如何检索值并将其放入小部件中?
class AddCashForm extends StatefulWidget {
@override
_AddCashFormState createState() => _AddCashFormState();
}
class _AddCashFormState extends State<AddCashForm> {
DateTime selectedDate = DateTime.now();
List<String> chipList = [
"one",
"two",
"three",
"four",
];
void dispose() {
oneController.dispose();
twoController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
ChoiceChipWidget(chipList, (item) {
print('Item selected: $item');
return (item);
}),
],
),
RaisedButton(
child: Text("Submit"),
onPressed: () {
},
),
// Text(item), data should appear here
],
),
);
}
}发布于 2019-10-15 00:19:20
您可以创建一个字段selectedItem,在选择项时对其进行更新。在onPressed方法中更新状态。就像这样:
class AddCashForm extends StatefulWidget {
@override
_AddCashFormState createState() => _AddCashFormState();
}
class _AddCashFormState extends State<AddCashForm> {
DateTime selectedDate = DateTime.now();
String selectedItem;
List<String> chipList = [
"one",
"two",
"three",
"four",
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
ChoiceChipWidget(chipList, (item) {
print('Item selected: $item');
selectedItem = item;
return (item);
})
],
),
RaisedButton(
child: Text("Submit"),
onPressed: () {
setState(() {});
},
),
// Text(item), data should appear here
],
),
);
}
}发布于 2019-10-15 00:36:39
如果希望项目自动更新,而不单击“提交”,请使用以下命令:
class _AddCashFormState extends State<AddCashForm> {
final selectedDate = DateTime.now();
final chipList = <String>[
'one',
'two',
'three',
'four',
];
String item;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: chipList
.map<Widget>((s) => ChoiceChip(
label: Text(s),
selected: s == item,
onSelected: (bool selected) {
setState(() {
item = selected ? s : null;
});
},
))
.toList(),
),
Text(item ?? ''),
],
),
);
}
}https://stackoverflow.com/questions/58384925
复制相似问题