如何根据下面的颤振代码为容器添加按下功能



这是我用来获取图像和文本的代码。我想知道如何在这里添加press

class Category {
final String name;
final String image;
Category(this.name, this.image);
}
List<Category> categories = categoriesData
.map((item) => Category(item['name'] as String, item['image'] as String))
.toList();
var categoriesData = [
{"name": "QR Scanner", 'image': "assets/images/imgone.png"},
{"name": "QR Generator", 'image': "assets/images/imgtwo.png"},
{
"name": "Calculator",
'image': "assets/images/imgthree.png"
},
{"name": "Text-To-Speech", 'image': "assets/images/imgfour.png"},
];

这里是代码,我调用上面的代码来显示图像和文本。前端。

Expanded(
child: StaggeredGridView.countBuilder(
crossAxisCount: 2,
itemCount: categories.length,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(20),
height: index.isEven ? 200:240,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
image: DecorationImage(
image: AssetImage(categories[index].image),
fit: BoxFit.fill,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(categories[index].name, style: kTitleTextStyle)
],
),
);
},

那么我如何添加到容器上?是的,我有5个容器,我想添加5个独立的函数。

GesuterDectector包裹gridItemcontainer,并使用onTap

并列出final List<Function> funcs = [(){}, myFunc, .....];

之类的功能列表演示部件

class MyWidgetX extends StatefulWidget {
MyWidgetX({Key? key}) : super(key: key);
@override
_MyWidgetXState createState() => _MyWidgetXState();
}
class _MyWidgetXState extends State<MyWidgetX> {
late List<Function> funcs;
myFun4() {
print("function 4 from funcList");
}
@override
void initState() {
super.initState();
funcs = [
() {
print("from funcList index is 0");
},
() {
print("from funcList index is 1");
},
() {
print("from funcList index is 2");
},
() {
print("from funcList index is 3");
},
myFun4,
];
}
@override
Widget build(BuildContext context) {
return StaggeredGridView.countBuilder(
staggeredTileBuilder: (int index) => new StaggeredTile.count(1, 1),
crossAxisCount: 2,
itemCount: funcs.length,
crossAxisSpacing: 20,
mainAxisSpacing: 20,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
if (index == 0) print("conditinal tapped  0");
if (index == 1) print("conditinal tapped  1");
funcs[index]();
},
child: Container(
padding: EdgeInsets.all(20),
height: index.isEven ? 200 : 240,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16),
),
child: Text("index $index")),
);
},
);
}
}

GestureDetectorInkWell包裹容器

GestureDetector(child: Container(),
onTap: () {
callFunction(); // call your function here 
});

但最好使用GestureDetector,它有很多你可以使用的参数。比如onTap(),它更像onPressed()函数

更多信息请查看docs

相关内容

  • 没有找到相关文章

最新更新