Flutter杂症(InkWell,TextField)

前言

这篇文章会记录一些再使用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试一下。

最后

文中的问题我会持续关注,有更好的解决办法会及时更新。

猜你喜欢

转载自juejin.im/post/5c3717a5518825265c2fd2c3
今日推荐