Home > Blockchain >  Flutter - Handle onChanged() to double in TextFormField
Flutter - Handle onChanged() to double in TextFormField

Time:01-07

in a "AlertDialog-Form" I want to use a ValueChanged callback for a double Variable. Using it in a TextFormField makes the error

The argument type 'void Function(double)' can't be assigned to the parameter type 'void Function(String)?'.

How to return it as a 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
        ,
      );
}

Here is the AlertDialog:

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

CodePudding user response:

Change your onChanged to this:

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

CodePudding user response:

You can change the function as RuslanBek commented,

final ValueChanged<String> onChangedGewicht;

But if you like to pass double, I will recommend using .tryParse instead of .parse so that you can handle exception on non-numeric string.

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