flutter的TextField参数、案例整理(上)

TextField

概述

  • TextField 用于文本输入

构造函数

复制代码
const TextField({
    Key key,
    this.controller, 
    this.focusNode,
    this.decoration = const InputDecoration(),
    TextInputType keyboardType,
    this.textInputAction,
    this.textCapitalization = TextCapitalization.none,
    this.style, // 文本样式
    this.strutStyle,
    this.textAlign = TextAlign.start, // 文本水平方向对齐方式
    this.textAlignVertical, // 本文垂直方向对齐方式
    this.textDirection, // 文本方向
    this.readOnly = false, // 是否是只读
    ToolbarOptions toolbarOptions,
    this.showCursor,
    this.autofocus = false, //在widget创建的时候是否自动获取焦点
    this.obscureText = false,// 是否隐藏文本,常用于密码输入
    this.autocorrect = true,
    this.enableSuggestions = true,
    this.maxLines = 1,
    this.minLines,
    this.expands = false,
    this.maxLength,//当设置了maxLength后,右下角会出现字数统计
    this.maxLengthEnforced = true,
    this.onChanged, // 内容发生改变方法回调
    this.onEditingComplete, // 完成编辑方法回调,实现了这个方法,键盘不再会自动收起
    this.onSubmitted, // 提交方法回调
    this.inputFormatters,// 用于校验,较麻烦,能搭配正则等使用
    this.enabled,
    this.cursorWidth = 2.0, // 光标宽度
    this.cursorRadius, // 光标圆角
    this.cursorColor, // 光标颜色
    this.keyboardAppearance,
    this.scrollPadding = const EdgeInsets.all(20.0), 
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true,
    this.onTap, // 点击方法回调(开始编辑)
    this.buildCounter, // 搭配maxLength出现的字数统计,控制字数统计的显示样式
    this.scrollController, // 滚动
    this.scrollPhysics,
  })

示例代码

  • 使用 TextEditingController 对 TextField 输入进行监听
    • 别忘记了释放TextEditingController

    • 可以获取输入框的文本、设置光标位置、清空输入框等操作

      /// 编辑框的控制器
      TextEditingController textEditingController = TextEditingController();
      /// 组件
      TextField(
      maxLines: 1,
      maxLength: 50,
      textInputAction: TextInputAction.search,
      style: const TextStyle(fontSize: 12, color: Colors.black),
      controller: textEditingController,
      onEditingComplete: onSearch,
      decoration: InputDecoration(
      /// 关闭计数器
      counterText: '',
      contentPadding: const EdgeInsets.symmetric(horizontal: 10),
      hintText: "输入你想搜索的内容",
      hintStyle: TextStyle(
      fontSize: 12, color: Global.theme.light_gray_color),
      hintMaxLines: 1,
      /// 直接用border: BorderSide.none会有布局问题,需要包裹OutlineInputBorder
      border: const OutlineInputBorder(
      // BorderSide(color: ) 设置边框颜色
      // borderRadius: const BorderRadius.all(Radius.circular(10.0)), 设置边框圆角
      borderSide: BorderSide.none
      ),
      suffixIcon: EIcon(
      width: 20,
      height: 20,
      path: "assets/icon/icon_search.png",
      onTap: onSearch),
      ),
      )
      /// 在页面里放上键盘监听
      KeyboardVisibilityBuilder(builder: (context, isKeyboardVisible) {
      dLog(_tag, "keyboard visible: $isKeyboardVisible");
      return emptyWidget;
      }),
      // 给全部添加一个GestureDetector,设置onTap方法
      // 方法内部加入FocusScope.of(context).unfocus();可以实现点击其他位置的地方让编辑框弹出的键盘隐藏
      // 本质是用了焦点来控制键盘的显隐

通过点击button控制键盘显隐

  • 搭配FocusNode

  • FocusNode,管理TextField的焦点

    class _TestWidgetState extends State<TestWidget> {
    // focusNode
    final FocusNode _focusNode = FocusNode(debugLabel: "Button");

    复制代码
    @override
    void initState() {
      super.initState();
      // 监听焦点
      _focusNode.addListener(() {
        if (_focusNode.hasFocus == true) {
          print("输入框获得焦点");
        } else {
          print("输入框失去焦点");
        }
      });
    }
    
    @override
    void dispose() {
      _focusNode.dispose();
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return Container(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Column(
          children: <Widget>[
            Center(
              child: TextField(
                focusNode: _focusNode,
              ),
            ),
            FlatButton(
              onPressed: () {
                if (_focusNode.canRequestFocus) {
                  FocusScope.of(context).requestFocus(_focusNode);
                }
              },
              child: Text('键盘弹出'),
            ),
            MaterialButton(
              onPressed: () {
                _focusNode.unfocus();
              },
              child: Text('键盘消失'),
            )
          ],
        ),
      );
    }

    }

相关推荐
yeziyfx2 小时前
Flutter 宽度充满屏幕的按钮
flutter
里欧跑得慢3 小时前
Flutter 组件 tavily_dart 的适配 鸿蒙Harmony 实战 - 驾驭 AI 搜索引擎集成、实现鸿蒙端互联网知识精密获取与语义增强方案
flutter·harmonyos·鸿蒙·openharmony·tavily_dart
国医中兴4 小时前
Flutter 三方库 pickled_cucumber 的鸿蒙化适配指南 - 玩转 BDD 行为驱动开发、Gherkin 自动化测试实战、鸿蒙级质量守护神
驱动开发·flutter·harmonyos
里欧跑得慢4 小时前
Flutter 三方库 config 的鸿蒙化适配指南 - 在鸿蒙系统上构建极致、透明、多源叠加的命令行参数解析与环境配置文件加载引擎
flutter·harmonyos·鸿蒙·openharmony
左手厨刀右手茼蒿4 小时前
Flutter 三方库 flutter_azure_tts 深度链接鸿蒙全场景智慧语音中枢适配实录:强势加载云端高拟真情感发音合成系统实现零延迟超自然多端协同-适配鸿蒙 HarmonyOS ohos
flutter·harmonyos·azure
雷帝木木4 小时前
Flutter 三方库 image_compare_2 的鸿蒙化适配指南 - 实现像素级的图像分块对比、支持感知哈希(pHash)与端侧视觉差异检测实战
flutter·harmonyos·鸿蒙·openharmony·image_compare_2
王码码20354 小时前
Flutter 三方库 sum_types 的鸿蒙化适配指南 - 引入函数式编程思维,让鸿蒙应用的状态处理更严谨
flutter·harmonyos·鸿蒙·openharmony·sum_types
加农炮手Jinx4 小时前
Flutter 三方库 cli_script 鸿蒙化极简命令行执行引擎适配探索:在多维沙盒终端环境注入异构 Shell 串联逻辑彻底拔高全自动化容器脚本运维及-适配鸿蒙 HarmonyOS ohos
运维·flutter·harmonyos
王码码20354 小时前
Flutter 三方库 simple_rsa 的鸿蒙化适配指南 - 实现非线性 RSA 密钥对生成与端侧文本加解密、支持标准公钥指纹验证与高强度数字签名实战
flutter·harmonyos·鸿蒙·openharmony·simple_rsa