[英]how to send a value from a widget to another on the same screen ? (flutter)
我正在尝试实现一个 slider,它在结帐时为初始值添加一个特定的值。 但我无法将额外的价值传递给我的结帐 API 调用。
这里是一个例子: https://imgur.com/a/mp5ytzW
我的 slider 在一个名为 DonationView 的 StatefullWidget 中实现,如下所示:
Widget getSlider(BuildContext context) {
return Slider(
min: 0,
max: 2000,
value: widget.extra.toDouble(),
onChanged: ((value) {
setState(() {
widget.extra = value.toInt();
});
}),
);
}
}
我想将值“额外”传递给 api 调用 fetchStripePaymentIntent
class DonateScreen extends StatefulWidget {
final int itemId;
final int conversationId;
final int extraInCent;
DonateScreen(@pathParam this.itemId, @pathParam this.conversationId, @pathParam this.extraInCent,
{Key? key})
: super(key: key);
@override
_DonateScreenState createState() => _DonateScreenState();
}
class _DonateScreenState extends State<DonateScreen> {
late Future<StripePaymentIntent> _stripePaymentIntent;
@override
void initState() {
super.initState();
setState(() {
_stripePaymentIntent = Provider.of<PaymentIntentProvider>(context, listen: false)
.fetchStripePaymentIntent(widget.itemId, widget.extraInCent);
});
}
@override
Widget build(BuildContext context) {
return BlocBuilder<ItemBloc, ItemState>(
builder: (context, state) {
if (state is ItemLoadedState) {
Item item = state.item;
return Scaffold(
appBar: AppBar(
title: Text(
"Pay".tr(),
),
),
body: SingleChildScrollView(
child: BlocBuilder<ProfileBloc, ProfileState>(
builder: ((context, state) {
if (state is ProfileLoadedState) {
UserProfile userProfile = state.userProfile;
return FutureBuilder<StripePaymentIntent>(
future: _stripePaymentIntent,
builder:
(BuildContext context, AsyncSnapshot<StripePaymentIntent> snapshot) {
List<Widget> children;
if (snapshot.hasData) {
Item theItem = item;
children = <Widget>[
BlocBuilder<NgosBloc, NgosState>(
builder: (context, state) {
if (state is NgosLoadedState) {
return Column(
children: [
DonateView(
snapshot.data!,
theItem,
userProfile,
widget.conversationId,
state.ngos[item.ngoId]!,
widget.extraInCent,
),
],
);
}
return Container();
},
),
];
预先感谢您的帮助
setState(() {
widget.extra = value.toInt();
});
这似乎很奇怪。 小部件成员应该是final
。 在setState()
中,您通常更新封闭State
class 的成员。
要在同一State
之外的小部件之间共享值,您应该查看state 管理。 这是必不可少的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.