首页 > 解决方案 > 在 null 上调用了 setter 'setValue='

问题描述

我正在尝试将输入值分配给我的模型,以便在 API POST 请求中使用它。但是,我不断收到错误消息:

setter was called on null when saving

模型:

@JsonSerializable()
class Discount {
  String value;

  Discount();

  set setValue(String value) { 
    this.value = value; 
  } 

飞镖代码:

                children: <Widget>[
                    Expanded(
                      child: Container(
                        margin: EdgeInsets.only(right: 5),
                        child: TextFormField(
                          initialValue: _invoiceFormData.discount?.value ?? '0.00',
                          inputFormatters: [_amountValidator],
                          keyboardType: TextInputType.numberWithOptions(
                            decimal: true,
                            signed: false,
                          ),
                          decoration: TextFormField.decoration(
                            labelText: Localizations.of(context)
                                .text('label_invoice_discount'),
                          ),
                          onChanged: (String value) {
                            setState(() {
                              discountTotal = value;
                        });   
                        },
                         onSaved: (value) => _invoiceFormData
                  .discount.setValue = value,
                        ),
                      ),
                    ),
                    FlatButton(
                        onPressed: () {
                          setState(() {
                          discountType = !discountType;
                          });
                        },                        
                     ),
                  ],

日志:

The setter 'setValue=' was called on null.
Receiver: null
Tried calling: setValue="10.00"

我尝试设置_invoiceFormData.discount.value = value但它仍然显示相同的错误。

标签: flutterdart

解决方案


_invoiceFormData.discount当您使用 setter 时,您的日志显示为 null setValue=

要解决此问题,您首先需要discount在名为 的对象中实例化该字段_invoiceFormData。例如,当您初始化此表单数据时(可能在您的 initState() 中),您应该这样做,_invoiceFormData.discount = Discount();然后它将不再为空


推荐阅读