当在Flutter中在TextFormField中输入文本时,如何使清除按钮出现

时间:2019-07-05 15:28:49

标签: flutter

我有一个表单,我希望清除按钮仅在用户开始输入数据时才出现在文本字段的右侧,而如果用户删除他在文本字段中输入的所有数据则消失。目前,我能够添加清除按钮,但它始终存在。

在下面查看我的代码

这是我的文本输入代码

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
        ),
       ),
      ]),
    );
  }
}

我希望当文本字段为空时清除(x按钮)消失,并在用户键入或从下拉菜单中选择一个值时出现(出现)。有人可以帮忙吗?预先感谢

1 个答案:

答案 0 :(得分:0)

您可以使用Dart的条件表达式来检查文本字段是否为空,然后不显示X按钮,否则显示它。例如,textController用于检索文本字段的值。您可以检查检索到的值是否大于0,然后显示X按钮,否则显示空container()。

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

注意:您需要在适用的代码行上方进行调整。

希望这有助于解决您的问题。