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·性能优化
恋猫de小郭11 小时前
Flutter Widget Preview 功能已合并到 master,提前在体验毛坯的预览支持
android·flutter·ios
小蜜蜂嗡嗡18 小时前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
瓜子三百克1 天前
十、高级概念
flutter
帅次1 天前
Objective-C面向对象编程:类、对象、方法详解(保姆级教程)
flutter·macos·ios·objective-c·iphone·swift·safari
小蜜蜂嗡嗡1 天前
flutter flutter_vlc_player播放视频设置循环播放失效、初始化后获取不到视频宽高
flutter
孤鸿玉2 天前
[Flutter小技巧] Row中widget高度自适应的几种方法
flutter
bawomingtian1232 天前
FlutterView 源码解析
flutter
Zender Han2 天前
Flutter 进阶:实现带圆角的 CircularProgressIndicator
flutter