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('键盘消失'),
            )
          ],
        ),
      );
    }

    }

相关推荐
庄雨山4 分钟前
深入解析Flutter动画体系:原理、实战与开源鸿蒙OpenHarmony对比
flutter·openharmonyos
kirk_wang7 分钟前
Flutter GPUImage 库在鸿蒙平台的 GPU 图像滤镜适配实战
flutter·移动开发·跨平台·arkts·鸿蒙
子榆.1 小时前
Flutter 与开源鸿蒙(OpenHarmony)离线能力与数据同步架构设计:打造高可用跨端应用
flutter·开源·harmonyos
晚烛1 小时前
实战前瞻:构建高韧性、可扩展的 Flutter + OpenHarmony 智慧政务服务平台
javascript·flutter·政务
西西学代码1 小时前
Flutter---常用打印图标
前端·python·flutter
ITKEY_2 小时前
flutter 运行windows版本 Nuget.exe not found解决办法
flutter
kirk_wang2 小时前
Flutter `flutter_statusbarcolor_ns` 在 OpenHarmony 平台的状态栏颜色适配实践
flutter·移动开发·跨平台·arkts·鸿蒙
不爱吃糖的程序媛2 小时前
开源鸿蒙跨平台赋能:Flutter/RN/KMP/CMP 多栈适配
flutter·开源·harmonyos
走在路上的菜鸟2 小时前
Android学Dart学习笔记第二十二节 类-扩展方法
android·笔记·学习·flutter
子榆.2 小时前
【2025 最新实践】Flutter 与 OpenHarmony 的“共生模式”:如何构建跨生态应用?(含完整项目架构图 + 源码)
flutter·华为·智能手机·electron