美文网首页
flutter 添加点击事件

flutter 添加点击事件

作者: 银弹星空 | 来源:发表于2021-05-24 15:37 被阅读0次

再给组件添加点击事件时,注意引用外部变量时,无法将闭包提取为方法。下边这样写在listView添加事件会变得混乱,而且不生效。

error: Cannot extract closure as method, it references 1 external variable(s)

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.yellow,
      body: Container(
        child: RefreshIndicator(
          onRefresh: _handleRefresh,
          child: ListView.builder(
            itemCount: list.length,
              itemBuilder: (BuildContext context,int index){
            return GestureDetector(
              onTap: _click(index),
              child: Container(
                height: 70,
                margin: EdgeInsets.all(50),
                child: Text('text$index'),),
            );
          }),
        ),
      ),
    );
    
  }
   _click(int index) {
   print('index$index');
   }

正确写法应该为下边这种写法

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.yellow,
      body: Container(
        child: RefreshIndicator(
          onRefresh: _handleRefresh,
          child: ListView.builder(
            itemCount: list.length,
              itemBuilder: (BuildContext context,int index){
            return GestureDetector(
              onTap: (){
                print('indexRight$index');
                Fluttertoast.showToast(msg: '展示$index');
              },
              child: Container(
                height: 70,
                margin: EdgeInsets.all(50),
                child: Text('text$index'),),
            );
          }),
        ),
      ),
    );
  }

相关文章

网友评论

      本文标题:flutter 添加点击事件

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