我想将单击的按钮添加到列表中,但是我不知道如何访问单击的按钮本身。
这是我的current list of Buttons。 通过以下方式创建:
for (var stand in stands) StandCreation(stand)
这是我要填写的列表:
List<String||Widget> SelectedStandList = []
这就是我创建每个“按钮”的方式:
import 'package:flutter/material.dart';
class StandCreation extends StatelessWidget {
final String stand;
StandCreation(this.stand);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () {}, // Here i would like to do something like SelectedStandList.add(tappedInkWell)
child: Container(
width: double.infinity,
margin: const EdgeInsets.only(
top: 5,
bottom: 5,
),
padding: const EdgeInsets.all(3.0),
color: Colors.blue,
child: Text(
stand,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 23,
fontWeight: FontWeight.bold,
),
),
),
);
}
}
然后我要使用列表创建一个仅包含所选项目的新屏幕。 感谢任何帮助!
答案 0 :(得分:2)
使用ListView.builder
而不是For
循环。将您的StandCreation
更改为此:
final VoidCallback onPressed;
StandCreation({this.stand, this.onPressed});
并将onTap
更改为此:
onTap: onPressed
最后将您的For循环更改为此:
ListView.builder(
itemCount: 6, // how many buttons you want
itemBuilder: (context, index) {
return StandCreation(stand: stand,
onPressed:(){
// Here is your onclick, do whatever you want with it
}
)
},
)
如果您希望每个onPressed
函数具有不同的操作,则可以在其中简单地放置一个If
语句:
onPressed:(){
if(index==0) //do something with first button
}