gpt4 book ai didi

flutter - 如何在flutter中向回调传递参数?

转载 作者:行者123 更新时间:2023-12-02 16:09:45 24 4
gpt4 key购买 nike

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,以便稍后可以更改价格的值。这给了我一个

error "1 required argument(s) expected, but 0 found"

但我无法将参数传递给 _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)),
],
);
}
}

最佳答案

您可以声明一个 Function 回调,如下所示:

final void Function(double price) changePrice;

这里是另一个例子,可以更好地理解它:

final bool Function(String id, double price) updateItem;

bool isPriceUpdated = widget.updateItem("item1", 7.5);

关于flutter - 如何在flutter中向回调传递参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com