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

    }

相关推荐
AiFlutter2 小时前
Flutter 获取手机连接的Wifi信息
flutter
刘志辉16 小时前
vue传参方法
android·vue.js·flutter
去伪存真19 小时前
聊聊Flutter与原生平台通信方式(一)
前端·flutter
Python私教1 天前
macOS 中搭建 Flutter 开发环境
flutter·macos
明似水1 天前
掌握 Flutter 中的 `Overlay` 和 `OverlayEntry`:弹窗管理的艺术
javascript·flutter
Flutter社区2 天前
使用 Flutter 3.19 更高效地开发
flutter·dart
Forever不止如此2 天前
【CustomPainter】绘制圆环
flutter·custompainter·圆环
wills7772 天前
Flutter Error: Type ‘UnmodifiableUint8ListView‘ not found
flutter
AiFlutter3 天前
Flutter之Package教程
flutter