flutter 抖动-处理onChanged()以在TextFormField中加倍

mccptt67  于 2023-01-09  发布在  Flutter
关注(0)|答案(2)|浏览(116)

在“AlertDialog-Form”中,我想对双精度变量使用ValueChanged回调。在TextFormField中使用它会导致错误
参数类型“void Function(double)”不能分配给参数类型“void Function(String)?”。
怎么把它当作双倍还回去?

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: () {},
            )
          ]),
    );
toe95027

toe950271#

将您的onChanged更改为:

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

isr3a4wc2#

正如RuslanBek所评论的,您可以更改函数,

final ValueChanged<String> onChangedGewicht;

但是如果您喜欢传递double,我建议使用.tryParse而不是.parse,这样您就可以处理非数字字符串上的异常。

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

相关问题