簡體   English   中英

使用另一個窗口小部件中的按鈕插入TextField-Flutter

[英]Insert into TextField using buttons from another widget - Flutter

我有一個TextField用作搜索欄,用戶可以在其中使用內置的Android / iOS鍵盤鍵入內容,也可以通過按鈕在搜索欄中插入特殊字符。 以某種方式將鍵入和另一插入組合到一個字符串中

用例:用戶在搜索欄中鍵入hell ,然后按按鈕小部件,搜索欄的值變為:hellö

我進行了所有設置,但是當我單擊按鈕時,什么也沒有發生(通過鍵盤鍵入可以正常工作)

這是我的代碼:

//I have this as a global variable
TextEditingController _searchInputControllor = TextEditingController();

//This is the TextField
class _SearchBarState extends State<SearchBar> { 
  @override
  Widget build(BuildContext context) {
    return TextField( 
    enableInteractiveSelection: false,                     
    controller: _searchInputControllor,
    cursorColor: primaryDark,
    decoration: InputDecoration(
      contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 15.0),
      border: InputBorder.none,
      hintText: "Search...",
      suffixIcon: Material(                     
        color: Colors.white,
        elevation: 6.0,
        borderRadius: BorderRadius.all(Radius.circular(6.0),),
        child: InkWell(
          splashColor: Colors.greenAccent,
          onTap: () {},
          child: Icon(Icons.search, color: primaryDark,),
         ),
       ),
     ),
   );
  }
} 

//This is the button widget
//It is supposed to add to the search bar but nothing happens
class _SpecialCharState extends State<SpecialChar> {
  @override
  Widget build(BuildContext context) {
    return ButtonTheme(
      minWidth: 40.0,
      child: FlatButton(
        color: Colors.transparent,
        textColor: Colors.black,
        padding: EdgeInsets.all(8.0),
        splashColor: Colors.blue,
        onPressed: () {
          setState(() {
            _searchInputControllor.text = _searchInputControllor.text + widget.btnVal.toLowerCase();
          });
        },
        child: Text(
          widget.btnVal
        ),
      )
    );
   }
  }

A.沒問題

我認為您的代碼運行良好,就像我在Android Phone 演示中嘗試的那樣。

當我點擊按鈕時,文本字段將更改。

B.更改光標位置

盡管如此,我還是添加了此代碼以使光標自動置於最后一個字符上。

我們將復制包含選擇內容的值,而不是直接更改文本。 稍后我們將其選擇偏移 newText的長度

void appendCharacters() {
  String oldText = _searchInputControllor.text;
  String newText = oldText + widget.btnVal.toLowerCase();

  var newValue = _searchInputControllor.value.copyWith(
    text: newText,
    selection: TextSelection.collapsed(
      offset: newText.length, //offset to Last Character
    ),
    composing: TextRange.empty,
  );

  _searchInputControllor.value = newValue;
}

因此我們可以使用以下代碼觸發該方法:

Widget build(BuildContext context) {
  return ButtonTheme(
    minWidth: 40.0,
    child: FlatButton(
      onPressed: appendCharacters, // call a function
    ),
  );
}

工作應用程序存儲庫

您可以查看此存儲庫並自己構建。 Github上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM