如何解决颤振中的提供商字符串问题?



你好,我很难改变一个小部件https://pub.dev/packages/stepper_counter_swipe的输入值。
我需要初始化参数initialValuestockQuantity背后的数量。
我得到了这个错误:

The following _CastError was thrown building _InheritedProviderScope<ProductManagmentModel?>(
value: Instance of 'ProductManagmentModel', 
listening to value):
type 'String' is not a subtype of type 'int' in type cast

使用以下代码

Selector<ProductManagmentModel, bool>(
builder: (_, manageStock, __) {
return Column(
children: [
if (manageStock)
StepperSwipe(
initialValue:stockQuantity1,
speedTransitionLimitCount: 3,
firstIncrementDuration: Duration(milliseconds: 300),
secondIncrementDuration: Duration(milliseconds: 100),
direction: Axis.horizontal,
dragButtonColor: Colors.blueAccent,
withSpring: true,
maxValue:1000,
minValue:0,
withFastCount: true,
stepperValue:widget.val,
onChanged: (val) {
model.product?.stockQuantity = int.parse(val.toString());
},
),
Row(
children: [
Checkbox(
value: manageStock,
onChanged: (val) {
model.updateManageStock();
}),
Text(S.of(context).manageStock),
],
),
],
);
},
selector: (_, provider) => provider.product!.manageStock),

stockQuantity1值是这样设置的

void _initController() {
final product =
Provider.of<ProductManagmentModel>(context, listen: false).product;
productNameController.text = product?.name ?? '';
regularPriceController.text = product?.regularPrice ?? '';
salePriceController.text = product?.salePrice ?? '';
sKUController.text = product?.sku ?? '';
stockQuantity.text = product?.stockQuantity.toString() ?? '';
shortDescription.text = product?.shortDescription ?? '';
description.text = product?.description ?? '';
tagsController.text =
product?.tags.map((e) => e.name).toList().join(',') ?? '';
stockQuantity1 = (product?.stockQuantity.toString()?? '') as int;
//stockQuantity1 = product?.stockQuantity as QuantityInputType;
}

当复选框未被选中时,值为空,我得到这个错误。当复选框被选中时,我没有这个问题。

谢谢你的帮助。

不妨多解释一下你的用例。

你在说"当复选框未被选中时,值为null,当复选框被选中时,我得到了这个错误,我没有那个问题">

所以当product?.stockQuantity=null时问题就发生了?

product?.stockQuantity=null时,initialValue值应该是多少?

从你的代码似乎,当product?.stockQuantitynull,stockQuantity1成为一个空字符串('')。或许可以把这部分改成0:

stockQuantity1 = (product?.stockQuantity.toString()?? 0) as int;

我用下面的命令解决了我的问题

if(product?.stockQuantity.toString() == 'null' ||product?.stockQuantity.toString() == null || stockQuantity.text == null || stockQuantity.text == 'null'   || stockQuantity == 'null'  || stockQuantity == null) {
//stockQuantity1=0 as int;
stockQuantity1 = (product?.stockQuantity ?? 0);
}
else  {
stockQuantity1 = (product?.stockQuantity ?? '') as int;
}

最新更新