【问题标题】:how to make clear button appears when text is enter in TextFormField in flutter在颤动的TextFormField中输入文本时如何使清除按钮出现
【发布时间】:2019-11-16 06:02:00
【问题描述】:

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

在下面查看我的代码

这是我的文本输入代码

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 按钮)在文本字段为空时消失,并在用户键入或从下拉列表中选择值等时出现。有人可以帮忙吗?提前致谢

【问题讨论】:

    标签: flutter


    【解决方案1】:

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

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

    注意:您需要根据您的代码调整上述行。

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

    【讨论】:

    • 嗨 DK15,感谢您的帮助。但是我应该在上面列出的代码中的哪个位置添加这一行?
    • 根据您提供的代码 sn-p,它可能会进入您正在呈现文本字段的 CustomTextField 类。只需查找您在哪里使用 X iconButton 并更新该代码。
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2021-06-28
    • 2021-09-17
    • 2014-02-27
    • 2018-09-20
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多