如何从ChoiceChip小部件中检索数据,并在按下按钮时将其传递给另一个小部件。
这是我的ChoiceChip
class ChoiceChipWidget extends StatefulWidget {
final List<String> reportList;
ChoiceChipWidget(this.reportList);
@override
_ChoiceChipWidgetState createState() => new _ChoiceChipWidgetState();
}
class _ChoiceChipWidgetState extends State<ChoiceChipWidget> {
String selectedChoice = "";
_buildChoiceList() {
List<Widget> choices = List();
widget.reportList.forEach((item) {
choices.add(Container(
child: ChoiceChip(
label: Text(item),
selected: selectedChoice == item,
onSelected: (selected) {
setState(() {
selectedChoice = item;
});
},
),
));
});
return choices;
}
@override
Widget build(BuildContext context) {
return Wrap(
children: _buildChoiceList(),
);
}
}
我想在按下按钮时在此小部件中传递它。
class AddCashForm extends StatefulWidget {
@override
_AddCashFormState createState() => _AddCashFormState();
}
class _AddCashFormState extends State<AddCashForm> {
List<String> chipList = [
"weekly",
"bi-weekly",
"monthly",
"once",
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new COHAppBar().getAppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
ChoiceChipWidget(chipList),
],
),
RaisedButton(
child: Text("Update Cash Flow"),
onPressed: () {
setState(() {});
},
),
//Text('${widget.selectedChoice ?? "File is empty"}'), Data goes here
],
),
);
}
}
... 我是否需要添加一个构造函数,以便在按下botton时可以传递数据?如何在这样的小部件之间传递数据
答案 0 :(得分:0)
您可以在按下事件中的RaisedButton中添加以下行:-
final Route route = MaterialPageRoute(builder: (context) => ChoiceChipWidget(true));
Navigator.push(mContext, route);
答案 1 :(得分:0)
您可以使用这样的回调函数:
class ChoiceChipWidget extends StatefulWidget {
final List<String> reportList;
final Function(String item) onItemSelected;
ChoiceChipWidget(this.reportList, this.onItemSelected);
@override
_ChoiceChipWidgetState createState() => new _ChoiceChipWidgetState();
}
选择该项目后,按如下所示调用函数:
onSelected: (selected) {
setState(() {
selectedChoice = item;
widget.onChoiceSelected(item);
});
}
然后,在创建窗口小部件时,您可以执行以下操作:
ChoiceChipWidget(chipList, (item) {
print('Item selected: $item');
})