Flutter — Cart Calculator App: Part 4

Hamza Mateen
3 min readApr 11, 2022

Improving TextField(s) input

Read previous parts here; Part-1, Part-2 and Part-3.

Resetting the TextFields:

Modify the onPressed() param of the ElevatedButton to clear TextFields and recalculate the cart total after an item is added. See below

setState(() {
_productNameController.clear();
_productQuantityController.clear();
_productPriceController.clear();
productsList.add(newProduct);
calculateTotal();
});

Currently, the TextFields in the add new product dialogs have only keyboard types given and we have to check the values after the button is tapped.

A better way would be to allow only a range of values to make sure the entered data is within the data domain.

Product Name Field

The product name field is expected to have 30 or fewer characters so we are checking it after the Add button is pressed. Alternatively, we can use the maxLength param to stop input of more than 30 characters.

maxLength: 30

This will also display a counter text under the field to as visual aid.

If you wish to remove the 0/30 counter text under the TextField, just override the counterText param inside decoration param and give it an empty string.

counterText: ""

If you wish to keep it but change its look, use the counterStyle param.

Product Quantity Field

Next, we wanted the quantity to be under 100 which means keeping the digit count to 2i.e. 99 maximum. Do the same as above and give maxLength: 2in decoration.
There is still something missing. The quantity can not be negative and there should not be a decimal point in between. So we use an advance param now.

inputFormatters allows giving custom regular expression to filter input to the TextField. For a value that contains only digits from 0 to 9, we can simply use the provided digitsOnly option.

Hamza Mateen

Front-End Development Lead at MiFinity | All about Flutter Application Development & Life in Ireland. Flutter App Developer | Lecturer | Writer.