如何访问刚刚单击的小部件或按钮的文本?
How to access the widget or the text of the button that was just clicked?
我想将被点击的按钮添加到列表中,但我不知道如何访问被点击的按钮本身。
这是我的current list of Buttons。
通过以下方式创建:
for (var stand in stands) StandCreation(stand)
这是我要填写的列表:
List<String||Widget> SelectedStandList = []
这就是我创建每个 'Button':
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,
),
),
),
);
}
}
然后我想使用列表创建一个仅包含所选项目的新屏幕。
感谢任何帮助!
使用 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
}
我想将被点击的按钮添加到列表中,但我不知道如何访问被点击的按钮本身。
这是我的current list of Buttons。 通过以下方式创建:
for (var stand in stands) StandCreation(stand)
这是我要填写的列表:
List<String||Widget> SelectedStandList = []
这就是我创建每个 'Button':
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,
),
),
),
);
}
}
然后我想使用列表创建一个仅包含所选项目的新屏幕。 感谢任何帮助!
使用 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
}