美文网首页Flutter中文社区FlutterFlutter圈子
flutter 踩坑(一):ListView内部控件点击事件

flutter 踩坑(一):ListView内部控件点击事件

作者: DarknessYami | 来源:发表于2019-01-16 00:09 被阅读20次

    ListView使用方式

    在flutter中listview的使用方式为:

    
    new RefreshIndicator(
                        child: new Center(
                            child: new ListView.builder(
                                itemCount: _getLength(),
                                itemBuilder: (BuildContext context,int position){
                                  return _getListData(position);
                                })
                        ),
                        onRefresh: _onEventRefresh),
    
    

    1.RefreshIndicator 是下拉刷新控件,child中包含下拉控件包裹的范围,onRefresh中包含下拉的要实现的方法。
    注意:onRefresh中的方法返回类型必须为Future<Null>,然后在该方法里面如果要用到异步方法,请用await 完成线程同步
    2.listview.builder 中itemCount 为获得的数据长度。
    3.getListData(position) 中实现item的布局。

    ListView Item的点击事件

    对于item的点击事件其实比较简单,只需要将item的布局用GestureDetector包裹起来,然后在onTap中处理点击事件即可。

    ListView内部控件的点击事件

    对于listview来说,如果不一定需要监听整个item的点击事件,而是只需要监听item中的某一个控件的点击事件,比如item中有一个按钮,只需要监听这个按钮的点击事件,这个怎么实现呢?
    首先我认为理所当然的在button中的onpressed 中去执行点击事件即可

    new Container(
                            alignment: Alignment.centerRight,
                            width: double.infinity,
                            child: new FlatButton(
                                onPressed: _readArticle(position),
                                child: new Text("查看全文",style: new TextStyle(color: Colors.blue),))
                            ,)
    

    在为没有任何点击的情况下输出结果为:


    输出信息

    很明显,在加载item的时候就已经触发了onPressed的事件,而且在点击按钮的时候也没有任何反应。
    网上的教程全是针对于item的点击事件,碰到这种问题其实是挺头痛的。

    解决方法

    emmm....后来仔细看了一下dart的语法之后,原来是onPressed里面的语法出现了问题,正确的应该是:

    new Container(
                            alignment: Alignment.centerRight,
                            width: double.infinity,
                            child: new FlatButton(
                                onPressed: () => _readArticle(position),
                                child: new Text("查看全文",style: new TextStyle(color: Colors.blue),))
                            ,)
    

    注意:()=> 符号表示传递的是回调函数,不使用的话表示直接执行这个函数, 看来还是要多了解dart的语法才行。

    相关文章

      网友评论

        本文标题:flutter 踩坑(一):ListView内部控件点击事件

        本文链接:https://www.haomeiwen.com/subject/mmoudqtx.html