使用回调在小部件之间传递/接收数据
例如,您声明一个回调和一个模型类,其中包含您要传递给子小部件的数据。
以下是子小部件的代码
class CustomerInformation extends StatefulWidget {
CustomerInformation({Key key, this.paymentModel, this.onContinue})
: super(key: key);
final VoidCallback onContinue;
final PullPaymentData paymentModel;
@override
State<StatefulWidget> createState() {
return _CustomerInformationState();
}
}
class _CustomerInformationState extends State<CustomerInformation> {
//useless code omitted
Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: RaisedButton(
onPressed: () async {
widget.onContinue();
}
},
child: Text(
Translations.of(context).sendOtpButton,
),
),
),
//useless code omitted
}
paymentModel 将作为 Ref 传递,并且当上面代码中的 RaisedButton 被按下时,控制权被转移回调用者(父级),它接收更新的模型:
以下是调用上述小部件的调用者(父)小部件的示例代码
class _PullPaymentScreenState extends State<PullPaymentScreen> {
PullPaymentData model = PullPaymentData(
identifier: "", isSendOtpSuccess: false, amount: "", currentStep: 0);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: getAppBar(),
body: Builder(builder: (BuildContext context) {
return Column(
children: <Widget>[
model.currentStep == 0
? CustomerInformation(
paymentModel: model,
onContinue: () {
//i recieve updated model HERE
setState(() {
if (model.isSendOtpSuccess) {
++model.currentStep;
Scaffold.of(context).showSnackBar(SnackBar(
content:
Text(Translations.of(context).otpSuccess),
duration: Duration(seconds: 4),
));
}
});
})
: SubmitPayment(
identifier: model.identifier,
amount: model.amount,
onResendPressed: () {
setState(() {
--model.currentStep;
});
},
),
],
);
}));
}