我在列表视图中遇到问题。我希望我的ListView项目提供按钮以对单个项目执行操作。但是我传递给他们的事件处理程序被意外地反复调用。但是,我希望仅在调用孩子的按钮时才能调用它。我做错了什么?
import 'package:flutter/material.dart';
import 'package:horaires_ratp/model/Database.dart';
class StationsList extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _StationsListState();
}
}
class _StationsListState extends State<StationsList> {
List<Station> _stations = List<Station>();
_StationsListState() {
Station().select().toList().then((value) {
setState(() {
_stations = value;
});
});
}
void _handleStationDelete(Station station){
//station.delete(true);
print("called");
Station().select().toList().then((value) {
setState(() {
_stations = value;
});
});
}
@override
Widget build(BuildContext context) {
return Container(
child: ListView.builder(
itemCount: _stations.length,
itemBuilder: (context, index) {
return StationComponent(_stations[index], _handleStationDelete);
}));
}
}
class StationComponent extends StatelessWidget {
final Station _station;
final Function _handleDelete;
StationComponent( this._station, this._handleDelete);
@override
Widget build(BuildContext context) {
return Container(
child: Card(
child: Container(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
Text(_station.name, textAlign: TextAlign.left),
IconButton(icon: Icon(Icons.delete), onPressed: _handleDelete(_station))
],
),
Row(
children: <Widget>[Row(children: <Widget>[])],
)
],
)),
),
);
}
}
您通过这样的功能
onPressed: onPressFunction
如果需要一些价值的话
onPressed: () => onPressFunction(value)
而且不喜欢
onPressed: onPressFunction(value)
所以你的代码应该是
IconButton(icon: Icon(Icons.delete), onPressed:() => _handleDelete(_station))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句