再给组件添加点击事件时,注意引用外部变量时,无法将闭包提取为方法。下边这样写在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'),),
);
}),
),
),
);
}