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

    }

相关推荐
ZFJ_张福杰1 小时前
【Flutter】Widget、Element和Render的关系-Flutter三棵树
flutter
vvilkim4 小时前
Flutter JSON解析全攻略:使用json_serializable实现高效序列化
flutter·json
LinXunFeng5 小时前
Flutter - GetX Helper 如何应用于旧页面
前端·flutter·开源
技术蔡蔡6 小时前
从Google IO学习Flutter
flutter·google·google io
vvilkim12 小时前
Flutter 状态管理基础:深入理解 setState 和 InheritedWidget
前端·javascript·flutter
97650333513 小时前
iOS 审核 cocos 4.3a【苹果机审的“分层阈值”设计】
flutter·游戏·unity·ios
程序员老刘·13 小时前
iOS 26 beta1 真机无法执行hot reload
flutter·ios·跨平台开发·客户端开发
ZFJ_张福杰15 小时前
【Flutter】性能优化总结
flutter·性能优化
BAGAE16 小时前
使用 Flutter 在 Windows 平台开发 Android 应用
android·大数据·数据结构·windows·python·flutter
肥肥呀呀呀1 天前
flutter 的lottie执行一次动画后关闭
开发语言·flutter