[flutter] Flutter 之编辑框 输入框TextField

[复制链接]
作者
n2n1   发布于2021-11-26 11:58:33 来自河北
flutter
flutter: 分享
截屏2021-11-26 上午11.56.35.png
TextField用于文本输入,它提供了很多属性,我们先简单介绍一下主要属性的作用,然后通过几个示例来演示一下关键属性的用法。
  1. const TextField({
  2.     Key key,
  3.     this.controller, //文本控制器
  4.     this.focusNode, //焦点控制
  5.     this.decoration = const InputDecoration(), //边框装饰
  6.     TextInputType keyboardType, // 键盘类型
  7.     this.textInputAction, //键盘的操作按钮
  8.     this.textCapitalization = TextCapitalization.none, //用户输入类型
  9.     this.style, //输入文本样式
  10.     this.strutStyle,
  11.     this.textAlign = TextAlign.start, //水平方向对齐方式。  值为  left、  right  、center、  justify 、 start、  end
  12.     this.textAlignVertical, // 文本垂直方向对齐方式 。 值为 top   、 center 、  bottom
  13.     this.textDirection,   //文本方向  rtl(right to left)   ltr(left to right)
  14.     this.readOnly = false,
  15.     ToolbarOptions toolbarOptions,   //工具栏选项的配置
  16.     this.showCursor,    //是否显示光标
  17.     this.autofocus = false,   //自动获取焦点
  18.     this.obscuringCharacter = '•',    //隐藏内容时,显示的文字
  19.     this.obscureText = false,  //  是否隐藏内容,例如密码格式
  20.     this.autocorrect = true,  //是否自动校正
  21.     SmartDashesType smartDashesType,   //指示如何处理文本输入中破折号的智能替换
  22.     SmartQuotesType smartQuotesType,  //指示如何处理文本输入中引号的智能替换。
  23.     this.enableSuggestions = true,  //启用建议
  24.     this.maxLines = 1,  //最大行数
  25.     this.minLines, //最小行数
  26.     this.expands = false, //
  27.     this.maxLength,  // 最多输入数,有值后右下角就会有一个计数器
  28.     this.maxLengthEnforced = true, //是否允许超过输入最大长度
  29.     this.onChanged, // 文本内容变更时回调
  30.     this.onEditingComplete,    // 输入完成回调 主要配合TextInputAction.done使用
  31.     this.onSubmitted,  //提交 配合TextInputAction
  32.     this.onAppPrivateCommand,
  33.     this.inputFormatters,   //输入校验
  34.     this.enabled,  //是否可用
  35.     this.cursorWidth = 2.0, // 光标宽度
  36.     this.cursorHeight, //光标高度
  37.     this.cursorRadius, //光标圆角
  38.     this.cursorColor, //光标颜色
  39.     this.selectionHeightStyle = ui.BoxHeightStyle.tight,
  40.     this.selectionWidthStyle = ui.BoxWidthStyle.tight,
  41.     this.keyboardAppearance,   // 键盘亮度
  42.     this.scrollPadding = const EdgeInsets.all(20.0),  // 滚动到视图中时,填充边距
  43.     this.dragStartBehavior = DragStartBehavior.start,
  44.     this.enableInteractiveSelection = true,    // 长按是否展示 剪切/复制/粘贴菜单
  45.     this.onTap,  //点击事件
  46.     this.mouseCursor, // 鼠标指针进入或悬停在鼠标指针上时的光标
  47.     this.buildCounter,
  48.     this.scrollController,  //控制可滚动的小部件
  49.     this.scrollPhysics, //确定[Scrollable]小部件的物理性质。
  50.     this.autofillHints,//自动填充提示
  51.     this.restorationId, //恢复ID以保存和恢复文本字段的状态。
复制代码
controller:编辑框的控制器,通过它可以设置/获取编辑框的内容、选择编辑内容、监听编辑文本改变事件。大多数情况下我们都需要显式提供一个controller来与文本框交互。如果没有提供controller,则TextField内部会自动创建一个。focusNode:用于控制TextField是否占有当前键盘的输入焦点。它是我们和键盘交互的一个句柄(handle)InputDecoration:用于控制TextField的外观显示,如提示文本、背景颜色、边框等。keyboardType:用于设置该输入框默认的键盘输入类型
InputDecoration

  1.   const InputDecoration({
  2.     this.icon,//左侧外的图标
  3.     this.labelText,//悬浮提示,可代替hintText
  4.     this.labelStyle,//悬浮提示文字的样式
  5.     this.helperText,//帮助文字
  6.     this.helperStyle,
  7.     this.hintText,//输入提示
  8.     this.hintStyle,
  9.     this.hintMaxLines,
  10.     this.errorText,//错误提示
  11.     this.errorStyle,
  12.     this.errorMaxLines,
  13.     this.hasFloatingPlaceholder = true,//是否显示悬浮提示文字
  14.     this.isDense,
  15.     this.contentPadding,//内填充
  16.     this.prefixIcon,//左侧内的图标
  17.     this.prefix, //左侧组件   
  18.     this.prefixText,//左侧内的文字
  19.     this.prefixStyle,
  20.     this.suffixIcon,//右侧内图标
  21.     this.suffix,  //右侧组件
  22.     this.suffixText,
  23.     this.suffixStyle,
  24.     this.counter,//自定义计数器
  25.     this.counterText,//计数文字
  26.     this.counterStyle,//计数样式
  27.     this.filled,//是否填充
  28.     this.fillColor,//填充颜色
  29.     this.errorBorder,
  30.     this.focusedBorder,
  31.     this.focusedErrorBorder,
  32.     this.disabledBorder,
  33.     this.enabledBorder,
  34.     this.border,//边框
  35.     this.enabled = true,
  36.     this.semanticCounterText,
  37.     this.alignLabelWithHint,
  38.   })
复制代码
prefix和prefixText 以及suffix和suffixText 不能同时存在
截屏2021-11-26 下午12.01.03.png
keyboardType[td]
TextInputType枚举值
含义
text
文本输入键盘
multiline
多行文本,需和maxLines配合使用(设为null或大于1)
number
数字;会弹出数字键盘
phone
优化后的电话号码输入键盘;会弹出数字键盘并显示“* #”
datetime
优化后的日期输入键盘;Android上会显示“: -”
emailAddress
优化后的电子邮件地址;会显示“@ .”
url
优化后的url输入键盘; 会显示“/ .”

示例:登录输入框

  1. import 'package:flutter/cupertino.dart';
  2. import 'package:flutter/material.dart';

  3. main() {
  4.   runApp(Myapp());
  5. }

  6. class Myapp extends StatelessWidget {
  7.   @override
  8.   Widget build(BuildContext context) {
  9.     return MaterialApp(
  10.       home: Scaffold(
  11.         appBar: AppBar(
  12.           title: Text("基础组件"),
  13.         ),
  14.         body: YshContent(),
  15.       ),
  16.     );
  17.   }
  18. }

  19. class YshContent extends StatelessWidget {
  20.   @override
  21.   Widget build(BuildContext context) {
  22.     return Column(
  23.       children: [
  24.         Padding(
  25.           padding: const EdgeInsets.all(8.0),
  26.           child: TextField(
  27.             decoration: InputDecoration(
  28.                 labelText: "请输入用户名",
  29.                 icon: Icon(Icons.people),
  30.                 hintText: "请输入用户名",
  31.                 prefixIcon: Icon(Icons.people_alt_rounded)),
  32.           ),
  33.         ),
  34.         Padding(
  35.           padding: const EdgeInsets.all(8.0),
  36.           child: TextField(
  37.             obscureText: true,
  38.             decoration: InputDecoration(
  39.               labelText: "请输入密码",
  40.               prefixIcon: Icon(Icons.lock),
  41.               hintText: "请输入密码",
  42.             ),
  43.           ),
  44.         ),
  45.       ],
  46.     );
  47.   }
  48. }
复制代码
截屏2021-11-26 下午12.02.13.png
获取输入内容
  • 获取输入内容有两种方式:
    • 定义两个变量,用于保存用户名和密码,然后在onChange触发时,各自保存一下输入内容。
    • 通过controller直接获取。

通过onChange获取
void onChanged(String value) {
print(value);
}
通过controller 获取
//定义一个controller
TextEditingController _controller = TextEditingController();
然后设置输入框controller:
TextField(
controller: _controller , //设置controller
...
)
通过controller获取输入框内容
print(_controller .text)
监听文本的变化通过onChange回调
通过controller监听
_controller .addListener(() {
print(_controller .text);
});
两种方式相比,onChanged是专门用于监听文本变化,而controller的功能却多一些,除了能监听文本变化外,它还可以设置默认值、选择文本

截屏2021-11-26 下午12.03.44.png
  1. _controller .selection=TextSelection(
  2.         baseOffset: 2,
  3.         extentOffset: _controller .text.length
  4.     );
复制代码


控制焦点这里我们就用到了focusNode
焦点可以通过FocusNode和FocusScopeNode来控制,默认情况下,焦点由FocusScope来管理,它代表焦点控制范围,可以在这个范围内可以通过FocusScopeNode在输入框之间移动焦点、设置默认焦点等。我们可以通过FocusScope.of(context) 来获取Widget树中默认的FocusScopeNode。


  1. class FocusTestRoute extends StatefulWidget {
  2.   @override
  3.   _FocusTestRouteState createState() => new _FocusTestRouteState();
  4. }

  5. class _FocusTestRouteState extends State<FocusTestRoute> {
  6.   FocusNode focusNode1 = new FocusNode();
  7.   FocusNode focusNode2 = new FocusNode();
  8.   FocusScopeNode focusScopeNode;

  9.   @override
  10.   Widget build(BuildContext context) {
  11.     return Padding(
  12.       padding: EdgeInsets.all(16.0),
  13.       child: Column(
  14.         children: <Widget>[
  15.           TextField(
  16.             autofocus: true,
  17.             focusNode: focusNode1,//关联focusNode1
  18.             decoration: InputDecoration(
  19.                 labelText: "input1"
  20.             ),
  21.           ),
  22.           TextField(
  23.             focusNode: focusNode2,//关联focusNode2
  24.             decoration: InputDecoration(
  25.                 labelText: "input2"
  26.             ),
  27.           ),
  28.           Builder(builder: (ctx) {
  29.             return Column(
  30.               children: <Widget>[
  31.                 RaisedButton(
  32.                   child: Text("移动焦点"),
  33.                   onPressed: () {
  34.                     //将焦点从第一个TextField移到第二个TextField
  35.                     // 这是一种写法 FocusScope.of(context).requestFocus(focusNode2);
  36.                     // 这是第二种写法
  37.                     if(null == focusScopeNode){
  38.                       focusScopeNode = FocusScope.of(context);
  39.                     }
  40.                     focusScopeNode.requestFocus(focusNode2);
  41.                   },
  42.                 ),
  43.                 RaisedButton(
  44.                   child: Text("隐藏键盘"),
  45.                   onPressed: () {
  46.                     // 当所有编辑框都失去焦点时键盘就会收起  
  47.                     focusNode1.unfocus();
  48.                     focusNode2.unfocus();
  49.                   },
  50.                 ),
  51.               ],
  52.             );
  53.           },
  54.           ),
  55.         ],
  56.       ),
  57.     );
  58.   }

  59. }


  60. // 监听焦点变化   
  61. focusNode.addListener((){
  62.    print(focusNode.hasFocus);
  63. });
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 创建账号

本版积分规则

Archiver|小黑屋|( 冀ICP备2021005463号 )

GMT+8, 2024-3-29 03:39 , Processed in 0.124535 second(s), 32 queries , Gzip On.

N2N1 It社区 n2n1.cn

Copyright © 2001-2021,MeiCheng.

快速回复 返回顶部 返回列表