在 flutter 应用程序中实现轮廓文本字段输入和标签文本

2024-04-25

我想要一个带有边框的文本字段输入,边框内有标签,如下图所示。先感谢您


我想你想要实现这样的目标。

  1. Inactive enter image description here
  2. Active enter image description here
  3. Validation enter image description here

您可以使用此小部件来实现此设计。

class OutlineBorderTextFormField extends StatefulWidget {
  FocusNode myFocusNode;
  TextEditingController tempTextEditingController;
  String labelText;
  TextInputType keyboardType;
  bool autofocus = false;
  TextInputAction textInputAction;
  List<TextInputFormatter> inputFormatters;
  Function validation;
  bool checkOfErrorOnFocusChange = false;//If true validation is checked when evre focus is changed

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _OutlineBorderTextFormField();
  }

  OutlineBorderTextFormField(
      {@required this.labelText,
      @required this.autofocus,
      @required this.tempTextEditingController,
      @required this.myFocusNode,
      @required this.inputFormatters,
      @required this.keyboardType,
      @required this.textInputAction,
      @required this.validation,
      @required this.checkOfErrorOnFocusChange});
}

class _OutlineBorderTextFormField extends State<OutlineBorderTextFormField> {
  bool isError = false;
  String errorString = "";

  getLabelTextStyle(color) {
    return TextStyle(
        fontSize: 12.0, color: color
    );
  } //label text style

  getTextFieldStyle() {
    return TextStyle(
        fontSize: 12.0,
        color: Colors.black,
    );
  } //textfield style

  getErrorTextFieldStyle() {
    return TextStyle(
        fontSize: 10.0,
        color: Colors.red,
    );
  }// Error text style

  getBorderColor(isfous) {
    return isfous
        ? Colors.deepPurple
        : Colors.black54;
  }//Border colors according to focus

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 16.0, top: 15.0, right: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          FocusScope(
            child: Focus(
              onFocusChange: (focus) {
                //Called when ever focus changes
                print("focus: $focus");
                setState(() {
                  getBorderColor(focus);
                  if (widget.checkOfErrorOnFocusChange &&
                      widget
                          .validation(widget.tempTextEditingController.text)
                          .toString()
                          .isNotEmpty) {
                    isError = true;
                    errorString = widget
                        .validation(widget.tempTextEditingController.text);
                  } else {
                    isError = false;
                    errorString = widget
                        .validation(widget.tempTextEditingController.text);
                  }
                });
              },
              child: Container(
                padding: EdgeInsets.all(2.0),
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                    borderRadius: BorderRadius.all(Radius.circular(
                            6.0) //                 <--- border radius here
                        ),
                    border: Border.all(
                      width: 1,
                      style: BorderStyle.solid,
                      color: isError
                          ? Colors.red
                          : getBorderColor(widget.myFocusNode.hasFocus),
                    )),
                child: TextFormField(
                  focusNode: widget.myFocusNode,
                  controller: widget.tempTextEditingController,
                  style: getTextFieldStyle(),
                  autofocus: widget.autofocus,
                  keyboardType: widget.keyboardType,
                  textInputAction: widget.textInputAction,
                  inputFormatters: widget.inputFormatters,
                  validator: (string) {
                    if (widget
                        .validation(widget.tempTextEditingController.text)
                        .toString()
                        .isNotEmpty) {
                      setState(() {
                        isError = true;
                        errorString = widget
                            .validation(widget.tempTextEditingController.text);
                      });
                      return "";
                    } else {
                      setState(() {
                        isError = false;
                        errorString = widget
                            .validation(widget.tempTextEditingController.text);
                      });
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                      labelText: widget.labelText,
                      labelStyle: isError
                          ? getLabelTextStyle(
                              Colors.red)
                          : getLabelTextStyle(Colors.deepPurple),
                      contentPadding:
                          EdgeInsets.symmetric(vertical: 7, horizontal: 16),
                      fillColor: Colors.grey[200],
                      filled: true,
                      enabledBorder: InputBorder.none,
                      errorBorder: InputBorder.none,
                      border: InputBorder.none,
                      errorStyle: TextStyle(height: 0),
                      focusedErrorBorder: InputBorder.none,
                      disabledBorder: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      hasFloatingPlaceholder: true),
                ),
              ),
            ),
          ),
          Visibility(
              visible: isError ? true : false,
              child: Container(
                  padding: EdgeInsets.only(left: 15.0, top: 2.0),
                  child: Text(
                    errorString,
                    style: getErrorTextFieldStyle(),
                  ))),
        ],
      ),
    );
    ;
  }
}

调用此小部件的示例

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  FocusNode myFocusNode = new FocusNode();
  TextEditingController tempTextEditingController = TextEditingController();

  FocusNode myFocusNode1 = new FocusNode();
  TextEditingController tempTextEditingController1 = TextEditingController();
  void validateAndSave() {
    final FormState form = _formKey.currentState;
    if (form.validate()) {
      print('Form is valid');
    } else {
      print('Form is invalid');
    }
  }
  String getTempIFSCValidation(String text) {
    return text.length > 5 ? "* Please enter valid IFSC Code" : "";
  }
  String getTempAccountValidation(String text) {
    return text.length > 8 ? "* Please enter valid Account Number" : "";
  }


  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            OutlineBorderTextFormField(labelText: "Account Number*",myFocusNode: myFocusNode,tempTextEditingController: tempTextEditingController,
             keyboardType: TextInputType.number,
            textInputAction: TextInputAction.next,
            autofocus: false,
            checkOfErrorOnFocusChange: true,
            inputFormatters: [
              LengthLimitingTextInputFormatter(18),
              WhitelistingTextInputFormatter.digitsOnly
            ],
            validation: (textToValidate){
              return getTempAccountValidation(textToValidate);
            },),
            OutlineBorderTextFormField(labelText: "Re- Enter Account Number*",myFocusNode: myFocusNode1,tempTextEditingController: tempTextEditingController1,
              keyboardType: TextInputType.number,
              textInputAction: TextInputAction.next,
              autofocus: false,
              checkOfErrorOnFocusChange: true,
              inputFormatters: [
                LengthLimitingTextInputFormatter(18),
                WhitelistingTextInputFormatter.digitsOnly
              ],
              validation: (textToValidate){
              print("Value Validated");
              return getTempIFSCValidation(textToValidate);
            },),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: validateAndSave,//call the validation method
        tooltip: 'Validate',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 flutter 应用程序中实现轮廓文本字段输入和标签文本 的相关文章

随机推荐

  • 如何检查.NET Core中是否存在配置节?

    如何检查配置节是否存在于appsettings json在 NET Core 中 即使某个部分不存在 以下代码也将始终返回一个实例化实例 e g var section this Configuration GetSection
  • Xcode10 - dyld:未加载框架中安装的 pod 的库

    我有一个带有目标框架的项目 主应用程序目标 框架A FrameworkA 是唯一使用某个 pod 的框架 因此在我的 pod 文件中我有类似的内容 target MainAppTarget do end target FrameworkA
  • 从更新面板异步回发后保持滚动位置

    我在使用 ASP NET 和更新面板时遇到一些问题 问题是 每次从更新面板发生部分回发时 页面都会滚动回顶部 在我的大多数页面上 这并不是一个大问题 但在某些页面上可能会变得很长 然后 当用户位于页面底部时 我显示 jQuery 弹出窗口R
  • 在 Sublime Text 3 中,我可以将 do 文件的选择发送到 Stata 吗?

    This SO question https stackoverflow com questions 18361667 is there a command line editor that highlights the stata syn
  • 为什么我删除的函数在 Node.js 中不是 typeof“undefined”?

    我正在使用 Node js 在我的 sum 函数被删除后 我希望 typeof sum 返回 undefined 但事实并非如此 functions are data in Javascript var sum function a b r
  • JQuery 模糊动画

    我使用以下脚本在单击按钮时模糊一个框 但如何使模糊需要 500 毫秒 document ready function attach click event to button button click function when butto
  • oracle sql if条件然后选择语句1 else选择语句2

    我有参数 prmtr我想要的是根据参数输入使用 select 语句 我试过这个 if prmtr A then select from tblA else select from tblB end if 但这是行不通的 还有其他方法可以做到
  • C++/OpenCV - 用于视频稳定的卡尔曼滤波器

    我尝试使用卡尔曼滤波器稳定视频以进行平滑 但我有一些问题 每次 我都有两帧 一帧是当前帧 另一帧是当前帧 这是我的工作流程 计算 goodFeaturesToTrack 使用 calcOpticalFlowPyrLK 计算光流 只保留优点
  • 在vb.net中将数据从DG和其他控件拖到另一个DG

    我在 VB Net 2010 中有表格 我想在 dgRegister 和日期 课程 ID 中单击并拖动多行 将其放入 dgCourseStudent 中 其中包含日期 注册 ID 注册名称和课程 ID 列 如何用vb net语言编写这个代码
  • 从 Visual Studio 搜索中排除特定文件

    是否可以从 Visual Studio 中的搜索中排除某些文件 例如 jquery js 几乎总是污染我的搜索结果 一半结果来自该文件 我知道您可以将特定类型列入白名单 但是当我想在 js 扩展名中搜索时 有解决方案吗 在这里投票功能 ht
  • 有没有办法使用 Paramiko 和 Python 来获取您连接的 SSH 服务器的横幅?

    有没有办法使用 Paramiko 和 Python 来获取您尝试连接的 SSH 服务器的横幅 我正在处理许多机器的超安全服务器设置过程 密码是通过预定义的密钥生成的 该密钥与 SSH 横幅一起打印出来 我可以访问将为我提供密码的实用程序 但
  • babeljs 无法正确转换扩展类[重复]

    这个问题在这里已经有答案了 我从这里得到了这个示例代码MDN https developer mozilla org en US docs Web JavaScript Reference Classes extends 稍微修改一下打印结
  • Windows 上的 MariaDB - 入门帮助?

    我正在尝试学习 MariaDB v5 2 4 但遇到了一些问题 我可以下载并安装它 但它似乎没有运行或者我丢失了一些东西 我正在为在 Windows 上运行的第一个计时器寻找一个好的资源 几个具体问题 是否需要 MySQL 才能运行 很多安
  • 有没有一个Java解析器可以解析这样的地址[重复]

    这个问题在这里已经有答案了 我正在使用 Java 6 我正在寻找一种自动解析地址的方法 我不关心地址是否存在 我发现的最好的东西是 JGeocoder v 0 4 1 但 JGeocoder 无法解析这样的地址 16th Street Th
  • 材质2调色板对比色

    在调色板中 我可以看到对比 如何选择对比色 works scss mat color button primary 不工作 scss mat color button primary contrast 900 看到底部写着对比 scss m
  • 如何在 PHP 中检测、删除和重定向末尾带有 # 的 url?

    客户要求我自动将任何带有井号的网址重定向到不带井号的版本 但我认为我没有使用此公式在任何网址中检测到 我使用 curPageURL 公式通过电子邮件给自己发送了一个示例 URL 它在我正在测试的 URL 中不包含尾随 符号 function
  • 在创建命名文件夹之前检查其是否存在

    我正在尝试将 Google Drive 中的特定文件插入到文件夹中 我还想检查是否有一个具有名称的文件夹 testFolder 如果是 则将文件插入到已存在的文件夹中 否则创建一个名为 testFolder 这是我到目前为止所想到的 但它总
  • 检测windows上的核心数

    如果我在 Linux 或 Mac 上运行 R 我可以使用以下命令检测可用内核的数量multicore detectCores 但是 没有 Windows 版本的多核功能 因此我无法在 Windows 上使用此技术 如何从 R 中以编程方式检
  • 从 Perl 守护程序运行时,为什么 FFMpeg 在五秒后停止?

    我用 Perl 编写了一个小守护程序 它调用 FFMpeg 对视频进行编码 但编码在 5 秒左右后停止 我用这段代码来启动它 my t echo ffmpeg command gt gt self gt FFMPEG OUTPUT my l
  • 在 flutter 应用程序中实现轮廓文本字段输入和标签文本

    我想要一个带有边框的文本字段输入 边框内有标签 如下图所示 先感谢您 我想你想要实现这样的目标 Inactive Active Validation 您可以使用此小部件来实现此设计 class OutlineBorderTextFormFi