当在Flutter中在TextFormField中输入文本时,如何使清除按钮出现 [英] how to make clear button appears when text is enter in TextFormField in flutter

查看:244
本文介绍了当在Flutter中在TextFormField中输入文本时,如何使清除按钮出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

在下面查看我的代码

这是我的文本输入代码

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按钮)消失,并在用户键入或从下拉菜单中选择一个值时出现(出现).有人可以帮忙吗?预先感谢

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

推荐答案

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

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.

这篇关于当在Flutter中在TextFormField中输入文本时,如何使清除按钮出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆