flutter - 如何使用 ontap 动态添加小部件
问题描述
我创建了一个嵌套的 for 循环,用于动态创建像小部件这样的按钮。就布局而言,一切都很顺利。但是,当我点击按钮时,点击功能将使用错误的按钮 id 执行(使用当前按钮 id 而不是我用来创建它的那个)(我用来创建按钮的索引)有没有人知道我应该如何解决这个问题?谢谢。
class ButtonItemsModel {
final String image;
final Color color;
final String title;
final String description;
final String ontap;
ButtonItemsModel({
@required this.color,
@required this.description,
@required this.image,
@required this.title,
@required this.ontap,
});
}
for (var row_count = 1; row_count <= _no_of_row; row_count++) {
buttoncells = [];
for (var button_cell_count = 1; button_cell_count <=
_rowwidgetno; button_cell_count++) {
if (buttonid >= buttonItems.length) {
break;
}
buttoncells.add(Padding(
padding: EdgeInsets.fromLTRB(
hpadding, vpadding, hpadding, vpadding),
child: Column(
children: [
Container(
width: button_width + 30,
child: Column(
children: [
Card(
// button color
elevation: (10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
color: buttonItems[buttonid].color,
child: InkWell(
customBorder: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
splashColor: Colors.red,
onTap: () async {
//here is the part that i have problems with
if (await canLaunch(
buttonItems[buttonid].ontap)) {
await launch(buttonItems[buttonid].ontap);
} else {
throw 'Could not launch' +
buttonItems[buttonid].ontap;
}
},
child:
Padding(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: SizedBox(
width: button_width, height: button_width,
child: Image(image: AssetImage(
buttonItems[buttonid].image),
)),
),
),
),
Text(buttonItems[buttonid].title),
],
)
)
]
),
),
);
buttonid = ((row_count - 1) * _rowwidgetno + button_cell_count);
}
buttonrow.add(Row(
children: buttoncells,
));
}
main_column = Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: buttonrow,
);
}
解决方案
推荐阅读
- flutter - 异常:Gradle 任务 assembleDebug 失败并出现退出代码
- linux - xv-6 make 显示为最新,即使有更改
- ios - WKWebview goBack 函数失败并出现 didFailNavigation 错误 kCFURLErrorCancelled
- angular - Angular - 从特定组件实例获取数据,以便能够通过单击按钮与之交互
- sql - PostgreSQL递归查询计算父值
- php - 启动 symfony 项目时出错(意外标记 `newline' 附近的语法错误)。会不会是php版本不兼容?
- python - (Python) 用于开发目的的进程启动器
- mysql - CakePHP 4 没有从 DB 中获取新添加的字段
- c# - c# blazor server - 将类对象从子级传递给父级
- excel - Case中的多个条件触发单元格更改