【问题标题】:Flutter - Handle onChanged() to double in TextFormFieldFlutter - 处理 onChanged() 以在 TextFormField 中加倍
【发布时间】:2023-01-07 18:59:47
【问题描述】:

在“AlertDialog-Form”中,我想对双变量使用 ValueChanged 回调。在 TextFormField 中使用它会出错

不能将参数类型“void Function(double)”分配给参数类型“void Function(String)?”。

如何将其返回为 double?

class GewichtFormWidget extends StatelessWidget {
  final double gewicht;
  final DateTime messzeitpunkt;
  final ValueChanged<double> onChangedGewicht;
  final ValueChanged<DateTime> onChangedDate;
  final VoidCallback onSavedGewicht;

  GewichtFormWidget({

    this.gewicht = 0,
    DateTime? messzeitpunkt,
    required this.onChangedGewicht,
    required this.onChangedDate,
    required this.onSavedGewicht,
  }) : this.messzeitpunkt = messzeitpunkt ?? DateTime.now(); 

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          buildGewicht(),
        ],
      ),
    );
  }

  Widget buildGewicht() => TextFormField(
        style: TextStyle(color: Colors.grey[800]),
        initialValue: gewicht.toString(),
        keyboardType: TextInputType.number,
        decoration: ThemeHelper()
            .textInputDecorationGreen('Gewicht', 'Gib das Gewicht ein.'),
        validator: (val) {
          if (val!.isEmpty) {
            return "Bitte gib ein Gewicht ein.";
          }
          return null;
        },
        onChanged: onChangedGewicht
        ,
      );
}

这是警报对话框:

return AlertDialog(
      content: 
//some other content
    GewichtFormWidget(
              onChangedGewicht: (gewicht) =>
                  setState((() => this.gewicht = gewicht)),
              onChangedDate: (messzeitpunkt) =>
                  setState((() => this.messzeitpunkt = messzeitpunkt)),
              onSavedGewicht: () {},
            )
          ]),
    );

【问题讨论】:

  • 将你的 double 传递参数转换为 string 因为你的函数的 parameter 数据类型必须是 string 类型

标签: flutter dart flutter-alertdialog


【解决方案1】:

将您的onChanged 更改为:

onChanged:(value){
  if(value != null){
    onChangedGewicht(double.parse(value));
  }
},

【讨论】:

    【解决方案2】:

    您可以像 RuslanBek 评论的那样更改功能,

    final ValueChanged<String> onChangedGewicht;
    

    但是如果你想传递双精度值,我会推荐使用.tryParse而不是.parse,这样你就可以处理非数字字符串的异常。

    onChanged: (value) =>onChangedGewicht(double.tryParse(value) ?? 0), 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 2022-08-11
      • 2021-11-15
      相关资源
      最近更新 更多