class ExtractArgumentsScreen extends StatelessWidget {
static const routeName = '/extractArguments';
double price = 0;
_changeprice(num){
setState(){
price+ = num;
}
}
@override
Widget build(BuildContext context) {
final MealArguments args = ModalRoute.of(context).settings.arguments;
return Scaffold(
appBar: AppBar(
title: Text('MyApp'),
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(height: 20,),
ViewCard(args.combo,_changeprice()),
]));
这是父类。我将函数_changePrice()传递给ViewCard,以便以后可以更改price的值。 这给我一个错误“预期有1个必需参数,但找到0个” 但我无法将参数传递给_changePrice,因为这违背了使用此回调的全部目的。 我要实现的内容与Emit the data to parent Widget in Flutter中建议的内容相似。 子类ViewCard将此回调传递给另一个名为OneItem的子类。
class OneItem extends StatefulWidget {
OneItem(this.combo, this.index, this.changePrice);
final Combo combo;
final int index;
final VoidCallback changePrice;
@override
State<StatefulWidget> createState() => OneItemState();
}
class OneItemState extends State<OneItem> {
List<bool> Vals = new List();
@override
void initState() {
super.initState();
int count = widget.combo.items.length;
Vals = List<bool>.generate(count, (_) => false);
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Align(
child: Text(widget.combo.items[widget.index].item),
alignment: Alignment(-1, 0),
),
Align(
child: Text(widget.combo.items[widget.index].price),
alignment: Alignment(0.1, 0)),
Align(
child: Checkbox(
value: Vals[widget.index],
onChanged: (bool value) {
setState(() {
Vals[widget.index] = value;
if(value == true){double childPrice = double.parse(widget.combo.items[widget.index].price); }
else{double val = double.parse(widget.combo.items[widget.index].price);
double childPrice = -1*val;}
widget.changePrice(childPrice);
//widget.changePrice();
});
},
),
alignment: Alignment(0.6, 0)),
],
);
}
}
答案 0 :(得分:0)
您从widget.changePrice(childPrice);
呼叫OneItemState
,所以changePrice
不能是VoidCallback
typedef IntCallback = Function(int num);
/* ... */
class OneItem extends StatefulWidget {
OneItem(this.combo, this.index, this.changePrice);
final Combo combo;
final int index;
final IntCallback changePrice;
@override
State<StatefulWidget> createState() => OneItemState();
}
/* ... */
ViewCard(args.combo, _changeprice) // function name without braces
我会这样
答案 1 :(得分:0)
您可以这样声明Function
回调:
final void Function(double price) changePrice;
这里有另一个例子可以更好地理解它:
final bool Function(String id, double price) updateItem;
bool isPriceUpdated = widget.updateItem("item1", 7.5);