Need to check a if entered value is a quantity in Flutter App

Viewed 64

Here I have added a stepper to insert price for a added product in the app. But is there any way I can check whether he actually added a price or something else. I'm kind of new to programming, so please help me.

Container(
                width: 150.0,
                child: TextFormField(
                  initialValue: widget.update ? order.price.toString() : null,
                  autocorrect: false,
                  onSaved: (String value) {
                    price = int.parse(value);
                  },
                  decoration: new InputDecoration(
                    labelText: "Price",
                    hintText: 'Price',
                    prefixText: "Rs.",
                  ),
                ),
              )

,

2 Answers

Add this parameter to your TextFormField: keyboardType: TextInputType.number,. So that user can only type in number. Example:

Container(
                width: 150.0,
                child: TextFormField(
                  initialValue: widget.update ? order.price.toString() : null,
                  autocorrect: false,
                  keyboardType: TextInputType.number,//this is the added line
                  onSaved: (String value) {
                    price = int.parse(value);
                  },
                  decoration: new InputDecoration(
                    labelText: "Price",
                    hintText: 'Price',
                    prefixText: "Rs.",
                  ),
                ),
              )

You can use both keyboardType: TextInputType.number and validator property in dart.

Container(
                width: 150.0,
                child: TextFormField(
                  initialValue: widget.update ? order.price.toString() : null,
                  autocorrect: false,
                  onSaved: (String value) {
                    price = int.parse(value);
                  },
                  validator: (value) {
                    if (value.isEmpty ||
                        !new RegExp(r'^[0-9]+$').hasMatch(value)) {
                      return 'Please enter valid price';
                    }
                  },
                  decoration: new InputDecoration(
                    labelText: "Price",
                    hintText: 'Price',
                    prefixText: "Rs.",
                  ),
                  keyboardType: TextInputType.number,
                ),
              ),

Refer this - https://flutter.dev/docs/cookbook/forms/validation

Related