How can I add on-press function to the containers according to the code below of flutter

Issue

Here’s the code I have used to fetch images and text. I wanna know how to add on press here.

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"},
];

And here’s the code, where I called the above code to show images and text. The frontend.

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)
                          ],
                        ),
                      );
                    },

So how can I add on press to the containers? And ya, I have 5 containers and I wanna add 5 separate functions.

Solution

Wrap your gridItem container with GesuterDectector and use onTap

and make a list of function like final List<Function> funcs = [(){}, myFunc, .....];

Demo Widget

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")),
        );
      },
    );
  }
}

Answered By – Yeasin Sheikh

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *