首页 > 解决方案 > How to check length of value in onchange method in flutter

问题描述

Check value of Textfield in onChange method is empty or not if user remove all values from Textfield show in TextView "0".

Mean I want real time change and show change in TextView.

examples:

when user add value its work fine

when user remove all values here is

TextFormField(
                          keyboardType: TextInputType.number,
                          textInputAction: TextInputAction.done,
                          maxLines: 1,
                          controller: _paidController,

                      onChanged: (text) {
                        int newValue = int.parse(text);
                        setState(() {
                          if (text.trim().isEmpty) {
                            _paidController.text = "0";

                            print("set 0");

                            unpaid = 0;
                            paid = 0;

                          } else {
                            paid = newValue;
                            unpaid = grandTotal.toInt() - paid;
                          }
                        });
                      },

                      onFieldSubmitted: (value) {
                        int newValue = int.parse(value);
                        setState(() {
                          if (value.isEmpty) {
                            paid = 0;
                            unpaid = grandTotal.toInt();
                          }
                          paid = newValue;
                          unpaid = grandTotal.toInt() - paid;
                        });
                      },
                      cursorColor: Theme.of(context).primaryColor,
                      style: TextStyle(
                        fontFamily: "Light",
                        color: Theme.of(context).primaryColor,
                      ),
                      decoration: InputDecoration(
                        filled: true,
                        fillColor: Colors.white,
                        labelStyle: TextStyle(
                          color: Color(0XFF17145A),
                          fontFamily: "Light",
                        ),
                        labelText: 'Paid Amount',
                      ),
                    ),

标签: flutterdart

解决方案


Use text.trim().isEmpty to check whether there has value on textField.

  onChanged: (text) {
      if (text.trim().isEmpty){
        _paidController.text = "0";  // set to zero if no value
        unpaid = grandTotal.toInt();
      }else{
        unpaid = grandTotal.toInt() - paid;
      }
   }

推荐阅读