Flutter雜症(InkWell,TextField)

三義廟范佩西發表於2019-01-11

前言

這篇文章會記錄一些再使用Flutter提供的Widget開發介面時碰到的一些小問題的解決方案和一些小技巧。在這之前我想說的是Flutter的github倉庫issue中milestones下有一個名為Golas的milestone,現在解決進度是30%。如果開發的時候碰到一些噁心的問題建議大家先去這裡搜搜,如果發現有相同的問題而且正好是那沒解決的70%。就別在這個問題上耽誤時間了(換別的思路)。

正文

問題:

InkWell設定背景色導致水波紋效果消失

new Container(
  color: Colors.red,
  child: new InkWell(
    onTap: (){},
  ),
);
複製程式碼

解決:

這裡問題其實出在了Container上,InkWell其是Material元件。使用Containe的效果其實是蓋住了Inkwell而不是給InkWell設定了背景色。正確的應該是(類似問題用這個方法大多可以解決):

new Material(
  color: Colors.red,
  child: new InkWell(),
)
複製程式碼

問題

TextFiled游標問題。看一下導致問題的程式碼。

class _MyHomePageState extends State<MyHomePage> {
  var _text = '';

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          title: new TextField(
        controller: new TextEditingController.fromValue(new TextEditingValue(text: _text)),
        autofocus: true,
      )),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {
            _text = "flutter";
          });
        },
        tooltip: 'Autocomplete',
        child: new Icon(Icons.add),
      ),
    );
  }
}
複製程式碼

再點選FloatingButton後你會發現游標會在輸入框的最前面。

解決

這個問題倒是不難解決,但總感覺怪怪的,每次set一個text還要設定一下游標的位置。

class _MyHomePageState extends State<MyHomePage> {
  var _text = "";

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
          title: new TextField(
        controller: new TextEditingController.fromValue(new TextEditingValue(
            text: _text,
            selection: new TextSelection.collapsed(offset: _text.length))),
        autofocus: true,
      )),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(() {
            _text = "flutter";
          });
        },
        tooltip: 'Autocomplete',
        child: new Icon(Icons.add),
      ),
    );
  }
}
複製程式碼

問題

TextFiled設定TextAlign為Center和Right游標就會出問題(Center現已修復)

動圖
動圖

解決

這個問題就坑爹了。暫時沒有太好的解決方法。有時候UI出了這種設計,可以參考微信的暱稱修改,點選跳轉下個介面輸入內容在儲存回來。

小技巧

有時候UI出了一個資訊錄入頁面,很多錄入項,外觀長都一樣,但是有的是輸入框,有的是點選選擇。我們這在時抽取UI的時候可能都會使用TextFiled。但TextField有自己的點選響應。這時候其實有兩個View來幫助我們(AbsorbPointer,IgnorePointer)來抵消TextField的點選響應。

用法:

new AbsorbPointer(
        child: new TextField(
          controller: new TextEditingController(
            text: "flutter",
          ),
        ),
      ),
複製程式碼

AbsorbPointer和IgnorePointer的區別,AbsorbPointer自身還可以響應點選事件,IgnorePointer自身則不可以。事例程式碼這裡就不展示了,感興趣的朋友那GestureDetector分別包裹AbsorbPointer和IgnorePointer試一下。

最後

文中的問題我會持續關注,有更好的解決辦法會及時更新。

相關文章