yoohoo
yoohoo

Reputation: 1217

how to make clear button appears when text is enter in TextFormField in flutter

I have a form where i want the clear button to appear on the right side of the textfield only when user start entering data and disappear if user delete all the data he input in the textfield. currently, i was able to add the clear button but it is there always.

see my code below

this is the code for my textiput

import 'package:flutter/material.dart';
import 'package:finsec/utils/hex_color.dart';

class CustomTextField extends StatelessWidget {
  CustomTextField({
    this.textInputType,
    this.textController ,
    this.errorMessage,
    this.labelText,
  });

  TextInputType textInputType;
  TextEditingController textController;
  String errorMessage, labelText;


  @override
  Widget build(BuildContext context) {
    bool isError = false;
    return  Container(

      child: TextFormField(
        keyboardType: textInputType,
        style: Theme
              .of(context)
              .textTheme
              .title,
        controller: textController,
        validator: (String value) {
            if (value.isEmpty) {
              return errorMessage;
            }
        },
        decoration: InputDecoration(
            suffixIcon: IconButton(
              onPressed: (){
                textController.clear();
              },
              icon: Icon(
                Icons.clear,
                color: Colors.grey,
              ),
            ),
          labelStyle: TextStyle(
            color: Colors.grey,
            fontSize: 16.0
          ),
        contentPadding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),  //size of textfield
        errorStyle: TextStyle(
          color: Colors.red,
          fontSize: 15.0
        ),
        border: OutlineInputBorder(
          borderSide:  BorderSide(width:5.0),
          borderRadius: BorderRadius.circular(5.0)
        )
        )
      ),
    );
  }
}


here is my code for the form
import 'package:flutter/material.dart';
import 'package:finsec/widget/row_text_input.dart';
import 'package:finsec/widget/text_form_field.dart';
import 'package:finsec/widget/save_button.dart';
import 'package:finsec/utils/strings.dart';
import 'package:finsec/utils/dimens.dart';
import 'package:finsec/utils/colors.dart';
import 'package:finsec/widget/column_text_input.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    title: 'Simple Interest Calculator App',
    home: ThirdFragment(),
    theme: ThemeData(
        brightness: Brightness.dark,
        primaryColor: Colors.indigo,
        accentColor: Colors.indigoAccent),
  ));
}

class ThirdFragment extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ThirdFragmentState();
  }
}

class _ThirdFragmentState extends State<ThirdFragment> {

  var _formKey = GlobalKey<FormState>();

  var _currencies = ['Rupees', 'Dollars', 'Pounds'];
  final double _minimumPadding = 5.0;

  var _currentItemSelected = '';

  @override
  void initState() {
    super.initState();
    _currentItemSelected = _currencies[0];
   // principalController.addListener(onChange);
  }



  TextEditingController amountController = TextEditingController();
  TextEditingController frequencyController = TextEditingController();
  TextEditingController datePaidController = TextEditingController();
  TextEditingController categoryController = TextEditingController();
  TextEditingController depositToController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();

  var displayResult = '';

  @override
  Widget build(BuildContext context) {
    TextStyle textStyle = Theme.of(context).textTheme.title;

    return Scaffold(
      appBar: AppBar(
        title: Text('Simple Interest Calculator'),
      ),
      body: Form(
        key: _formKey,
          onChanged: ,
        child: SingleChildScrollView(
          child: Column (children: [

            Padding(
              padding: EdgeInsets.only(top: 10.0, bottom: 5.0, left: 15.0, right: 15.0),
              child: CustomTextField(textInputType:TextInputType.number,
                textController: amountController,
                errorMessage:'Enter Income Amount',
                labelText:'Income Amount for testing'),
            ),
            RowTextInput(inputName: 'Frequency:',
              textInputType: TextInputType.number,
              textController: frequencyController,
              errorMessage: 'Choose Income Frequency',
              labelText: 'Income Amount for testing'
            ),
            RowTextInput(inputName: 'Date Paid:',
                textInputType: TextInputType.number,
                textController: datePaidController,
                errorMessage: 'Pick Income Payment Date',
                labelText: 'Income Amount for testing'
            ),
            RowTextInput(inputName: 'Category:',
                textInputType: TextInputType.number,
                textController: categoryController,
                errorMessage: 'Enter Income Category',
                labelText: 'Income Amount for testing'
            ),
            RowTextInput(inputName: 'Deposit To:',
                textInputType: TextInputType.number,
                textController: depositToController,
                errorMessage: 'Choose Bank Acct Where Income Is Deposited',
                labelText: 'Income Amount for testing'
            ),
            RowTextInput(inputName: 'Description:',
                textInputType: TextInputType.number,
                textController: descriptionController,
                errorMessage: 'Please enter principal amount',
                labelText: 'Income Amount for testing'
            ),
            SizedBox(height: 20),
            //saveButton()

          Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                MaterialButton(
                  height: margin_40dp,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(margin_5dp)),
                  minWidth: (MediaQuery.of(context).size.width * .9) / 2,
                  color: Theme.of(context).primaryColor,
                  textColor: white,
                  child: new Text(save),
                  onPressed: () => {
                  setState(() {
                  if (_formKey.currentState.validate()) {
                    // amountController.text.isEmpty ? amountController.text='Value require' : amountController.text='';
                  //this.displayResult = _calculateTotalReturns();
                  }
                  })
                  },
                  splashColor: blueGrey,
                ),
                MaterialButton(
                  height: margin_40dp,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(margin_5dp)),
                  minWidth: (MediaQuery.of(context).size.width * .9) / 2,
                  color: Theme.of(context).primaryColor,
                  textColor: white,
                  child: new Text(save_and_continue),
                  onPressed: () => {},
                  splashColor: blueGrey,
                )
              ])
          ]
          ),
      ),

      ),
    );
  }

}

import 'package:flutter/material.dart';
import 'package:finsec/widget/text_form_field.dart';

class RowTextInput extends StatelessWidget {
  RowTextInput({
    this.inputName,
    this.textInputType,
    this.textController ,
    this.errorMessage,
    this.labelText,
    // this.hint,
    // this.height,
    // this.padding,
    //  this.headerRadius,
  });

  TextInputType textInputType;
  TextEditingController textController;
  String inputName, errorMessage, labelText;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
      top: 5.0, bottom: 5.0, left: 15.0, right: 15.0),
      child: Row(children: [
        Expanded(
          child: Text(this.inputName,  maxLines: 1,)
        ),
       Expanded(
        flex: 3,
        child: CustomTextField(textInputType:TextInputType.number,
            textController: this.textController,
            errorMessage: this.errorMessage
        ),
       ),
      ]),
    );
  }
}

i am expecting the clear (x button) to disappear when textfield is empty and appear when user type or select a value from dropdown etc. can someone help? thanks in advance

Upvotes: 3

Views: 4329

Answers (1)

Darshan
Darshan

Reputation: 11669

You can make use of Dart's conditional expression to check if textfield is empty then don't show X button else show it. For ex, the textController is used to retrieve value of textfield. You can check if the value retrieved is greater than 0 then show X button, else show empty container().

textController.text.length > 0 ? IconButton(icon: Icon(Icons.clear), onPressed: () {} : Container()

Note: You will need to adjust above line w.r.t your code as applicable.

Hope this helps and resolves your issue.

Upvotes: 2

Related Questions