Flutter 之 輸入框TextField

Material組件庫(kù)中提供了輸入框組件TextField

TextField

效果圖

TextField用于文本輸入贾富,它提供了很多屬性行瑞,我們先簡(jiǎn)單介紹一下主要屬性的作用秩命,然后通過(guò)幾個(gè)示例來(lái)演示一下關(guān)鍵屬性的用法。

 const TextField({
    Key key,
    this.controller, //文本控制器
    this.focusNode, //焦點(diǎn)控制
    this.decoration = const InputDecoration(), //邊框裝飾
    TextInputType keyboardType, // 鍵盤類型
    this.textInputAction, //鍵盤的操作按鈕
    this.textCapitalization = TextCapitalization.none, //用戶輸入類型
    this.style, //輸入文本樣式
    this.strutStyle,
    this.textAlign = TextAlign.start, //水平方向?qū)R方式蟹略。  值為  left缓淹、  right  哈打、center、  justify 讯壶、 start料仗、  end
    this.textAlignVertical, // 文本垂直方向?qū)R方式 。 值為 top   伏蚊、 center 立轧、  bottom
    this.textDirection,   //文本方向  rtl(right to left)   ltr(left to right)
    this.readOnly = false,
    ToolbarOptions toolbarOptions,   //工具欄選項(xiàng)的配置
    this.showCursor,    //是否顯示光標(biāo)
    this.autofocus = false,   //自動(dòng)獲取焦點(diǎn)
    this.obscuringCharacter = '?',    //隱藏內(nèi)容時(shí),顯示的文字
    this.obscureText = false,  //  是否隱藏內(nèi)容,例如密碼格式
    this.autocorrect = true,  //是否自動(dòng)校正
    SmartDashesType smartDashesType,   //指示如何處理文本輸入中破折號(hào)的智能替換
    SmartQuotesType smartQuotesType,  //指示如何處理文本輸入中引號(hào)的智能替換氛改。
    this.enableSuggestions = true,  //啟用建議
    this.maxLines = 1,  //最大行數(shù)
    this.minLines, //最小行數(shù)
    this.expands = false, //
    this.maxLength,  // 最多輸入數(shù)匀借,有值后右下角就會(huì)有一個(gè)計(jì)數(shù)器
    this.maxLengthEnforced = true, //是否允許超過(guò)輸入最大長(zhǎng)度
    this.onChanged, // 文本內(nèi)容變更時(shí)回調(diào)
    this.onEditingComplete,    // 輸入完成回調(diào) 主要配合TextInputAction.done使用
    this.onSubmitted,  //提交 配合TextInputAction
    this.onAppPrivateCommand,
    this.inputFormatters,   //輸入校驗(yàn)
    this.enabled,  //是否可用
    this.cursorWidth = 2.0, // 光標(biāo)寬度
    this.cursorHeight, //光標(biāo)高度
    this.cursorRadius, //光標(biāo)圓角
    this.cursorColor, //光標(biāo)顏色
    this.selectionHeightStyle = ui.BoxHeightStyle.tight,
    this.selectionWidthStyle = ui.BoxWidthStyle.tight,
    this.keyboardAppearance,   // 鍵盤亮度
    this.scrollPadding = const EdgeInsets.all(20.0),  // 滾動(dòng)到視圖中時(shí),填充邊距
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true,    // 長(zhǎng)按是否展示 剪切/復(fù)制/粘貼菜單
    this.onTap,  //點(diǎn)擊事件
    this.mouseCursor, // 鼠標(biāo)指針進(jìn)入或懸停在鼠標(biāo)指針上時(shí)的光標(biāo)
    this.buildCounter,
    this.scrollController,  //控制可滾動(dòng)的小部件
    this.scrollPhysics, //確定[Scrollable]小部件的物理性質(zhì)平窘。
    this.autofillHints,//自動(dòng)填充提示
    this.restorationId, //恢復(fù)ID以保存和恢復(fù)文本字段的狀態(tài)。

屬性詳解

  • controller:編輯框的控制器凳怨,通過(guò)它可以設(shè)置/獲取編輯框的內(nèi)容瑰艘、選擇編輯內(nèi)容、監(jiān)聽(tīng)編輯文本改變事件肤舞。大多數(shù)情況下我們都需要顯式提供一個(gè)controller來(lái)與文本框交互紫新。如果沒(méi)有提供controller,則TextField內(nèi)部會(huì)自動(dòng)創(chuàng)建一個(gè)李剖。
  • focusNode:用于控制TextField是否占有當(dāng)前鍵盤的輸入焦點(diǎn)芒率。它是我們和鍵盤交互的一個(gè)句柄(handle)
  • InputDecoration:用于控制TextField的外觀顯示,如提示文本篙顺、背景顏色偶芍、邊框等。
  • keyboardType:用于設(shè)置該輸入框默認(rèn)的鍵盤輸入類型

InputDecoration

  const InputDecoration({
    this.icon,//左側(cè)外的圖標(biāo)
    this.labelText,//懸浮提示德玫,可代替hintText
    this.labelStyle,//懸浮提示文字的樣式
    this.helperText,//幫助文字
    this.helperStyle,
    this.hintText,//輸入提示
    this.hintStyle,
    this.hintMaxLines,
    this.errorText,//錯(cuò)誤提示
    this.errorStyle,
    this.errorMaxLines,
    this.hasFloatingPlaceholder = true,//是否顯示懸浮提示文字
    this.isDense,
    this.contentPadding,//內(nèi)填充
    this.prefixIcon,//左側(cè)內(nèi)的圖標(biāo)
    this.prefix, //左側(cè)組件   
    this.prefixText,//左側(cè)內(nèi)的文字
    this.prefixStyle,
    this.suffixIcon,//右側(cè)內(nèi)圖標(biāo)
    this.suffix,  //右側(cè)組件
    this.suffixText, 
    this.suffixStyle,
    this.counter,//自定義計(jì)數(shù)器
    this.counterText,//計(jì)數(shù)文字
    this.counterStyle,//計(jì)數(shù)樣式
    this.filled,//是否填充
    this.fillColor,//填充顏色
    this.errorBorder,
    this.focusedBorder,
    this.focusedErrorBorder,
    this.disabledBorder,
    this.enabledBorder,
    this.border,//邊框
    this.enabled = true,
    this.semanticCounterText,
    this.alignLabelWithHint,
  })

注意

prefix和prefixText 以及suffix和suffixText 不能同時(shí)存在



keyboardType

TextInputType枚舉值 含義
text 文本輸入鍵盤
multiline 多行文本匪蟀,需和maxLines配合使用(設(shè)為null或大于1)
number 數(shù)字;會(huì)彈出數(shù)字鍵盤
phone 優(yōu)化后的電話號(hào)碼輸入鍵盤宰僧;會(huì)彈出數(shù)字鍵盤并顯示“* #”
datetime 優(yōu)化后的日期輸入鍵盤材彪;Android上會(huì)顯示“: -”
emailAddress 優(yōu)化后的電子郵件地址;會(huì)顯示“@ .”
url 優(yōu)化后的url輸入鍵盤琴儿; 會(huì)顯示“/ .”

示例:登錄輸入框

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

main() {
  runApp(Myapp());
}

class Myapp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("基礎(chǔ)組件"),
        ),
        body: YshContent(),
      ),
    );
  }
}

class YshContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            decoration: InputDecoration(
                labelText: "請(qǐng)輸入用戶名",
                icon: Icon(Icons.people),
                hintText: "請(qǐng)輸入用戶名",
                prefixIcon: Icon(Icons.people_alt_rounded)),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: TextField(
            obscureText: true,
            decoration: InputDecoration(
              labelText: "請(qǐng)輸入密碼",
              prefixIcon: Icon(Icons.lock),
              hintText: "請(qǐng)輸入密碼",
            ),
          ),
        ),
      ],
    );
  }
}

登錄

獲取輸入內(nèi)容

  • 獲取輸入內(nèi)容有兩種方式:
    • 定義兩個(gè)變量段化,用于保存用戶名和密碼,然后在onChange觸發(fā)時(shí)造成,各自保存一下輸入內(nèi)容显熏。
    • 通過(guò)controller直接獲取。

通過(guò)onChange獲取
void onChanged(String value) {
print(value);
}

通過(guò)controller 獲取
//定義一個(gè)controller
TextEditingController _controller = TextEditingController();
然后設(shè)置輸入框controller:
TextField(
controller: _controller , //設(shè)置controller
...
)
通過(guò)controller獲取輸入框內(nèi)容
print(_controller .text)

監(jiān)聽(tīng)文本的變化

通過(guò)onChange回調(diào)
通過(guò)controller監(jiān)聽(tīng)
_controller .addListener(() {
print(_controller .text);
});

兩種方式相比谜疤,onChanged是專門用于監(jiān)聽(tīng)文本變化佃延,而controller的功能卻多一些,除了能監(jiān)聽(tīng)文本變化外夷磕,它還可以設(shè)置默認(rèn)值履肃、選擇文本

文本選中
_controller .selection=TextSelection(
        baseOffset: 2,
        extentOffset: _controller .text.length
    );

控制焦點(diǎn)

這里我們就用到了focusNode

焦點(diǎn)可以通過(guò)FocusNode和FocusScopeNode來(lái)控制,默認(rèn)情況下坐桩,焦點(diǎn)由FocusScope來(lái)管理尺棋,它代表焦點(diǎn)控制范圍,可以在這個(gè)范圍內(nèi)可以通過(guò)FocusScopeNode在輸入框之間移動(dòng)焦點(diǎn)、設(shè)置默認(rèn)焦點(diǎn)等膘螟。我們可以通過(guò)FocusScope.of(context) 來(lái)獲取Widget樹(shù)中默認(rèn)的FocusScopeNode成福。

class FocusTestRoute extends StatefulWidget {
  @override
  _FocusTestRouteState createState() => new _FocusTestRouteState();
}

class _FocusTestRouteState extends State<FocusTestRoute> {
  FocusNode focusNode1 = new FocusNode();
  FocusNode focusNode2 = new FocusNode();
  FocusScopeNode focusScopeNode;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: Column(
        children: <Widget>[
          TextField(
            autofocus: true, 
            focusNode: focusNode1,//關(guān)聯(lián)focusNode1
            decoration: InputDecoration(
                labelText: "input1"
            ),
          ),
          TextField(
            focusNode: focusNode2,//關(guān)聯(lián)focusNode2
            decoration: InputDecoration(
                labelText: "input2"
            ),
          ),
          Builder(builder: (ctx) {
            return Column(
              children: <Widget>[
                RaisedButton(
                  child: Text("移動(dòng)焦點(diǎn)"),
                  onPressed: () {
                    //將焦點(diǎn)從第一個(gè)TextField移到第二個(gè)TextField
                    // 這是一種寫法 FocusScope.of(context).requestFocus(focusNode2);
                    // 這是第二種寫法
                    if(null == focusScopeNode){
                      focusScopeNode = FocusScope.of(context);
                    }
                    focusScopeNode.requestFocus(focusNode2);
                  },
                ),
                RaisedButton(
                  child: Text("隱藏鍵盤"),
                  onPressed: () {
                    // 當(dāng)所有編輯框都失去焦點(diǎn)時(shí)鍵盤就會(huì)收起  
                    focusNode1.unfocus();
                    focusNode2.unfocus();
                  },
                ),
              ],
            );
          },
          ),
        ],
      ),
    );
  }

}


// 監(jiān)聽(tīng)焦點(diǎn)變化    
focusNode.addListener((){
   print(focusNode.hasFocus);
});

參考

Flutter實(shí)戰(zhàn)
https://blog.csdn.net/yechaoa/article/details/90906689

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市荆残,隨后出現(xiàn)的幾起案子奴艾,更是在濱河造成了極大的恐慌,老刑警劉巖内斯,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蕴潦,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡俘闯,警方通過(guò)查閱死者的電腦和手機(jī)潭苞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)真朗,“玉大人此疹,你說(shuō)我怎么就攤上這事≌谏簦” “怎么了蝗碎?”我有些...
    開(kāi)封第一講書人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)旗扑。 經(jīng)常有香客問(wèn)我衍菱,道長(zhǎng),這世上最難降的妖魔是什么肩豁? 我笑而不...
    開(kāi)封第一講書人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任脊串,我火速辦了婚禮,結(jié)果婚禮上清钥,老公的妹妹穿的比我還像新娘琼锋。我一直安慰自己,他們只是感情好祟昭,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布缕坎。 她就那樣靜靜地躺著,像睡著了一般篡悟。 火紅的嫁衣襯著肌膚如雪谜叹。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 51,679評(píng)論 1 305
  • 那天搬葬,我揣著相機(jī)與錄音荷腊,去河邊找鬼。 笑死急凰,一個(gè)胖子當(dāng)著我的面吹牛女仰,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼疾忍,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼乔外!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起一罩,我...
    開(kāi)封第一講書人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤杨幼,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后聂渊,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體推汽,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年歧沪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片莲组。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡诊胞,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出锹杈,到底是詐尸還是另有隱情撵孤,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布竭望,位于F島的核電站邪码,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏咬清。R本人自食惡果不足惜闭专,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望旧烧。 院中可真熱鬧影钉,春花似錦、人聲如沸掘剪。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)夺谁。三九已至廉赔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間匾鸥,已是汗流浹背蜡塌。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留勿负,地道東北人岗照。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親攒至。 傳聞我的和親對(duì)象是個(gè)殘疾皇子厚者,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容