flutter 使用ListView中的Tap功能

j8yoct9x  于 2023-01-31  发布在  Flutter
关注(0)|答案(2)|浏览(131)

我正在测试列表视图中项目的"点击功能",但它似乎不起作用。当我点击列表时,打印功能不起作用。

return Scaffold(
          appBar: AppBar(
            // App Bar
            title: Text(
              "ListView On-Click Event",
              style: TextStyle(color: Colors.grey),
            ),
            elevation: 0,
            backgroundColor: Colors.white,
          ),
          // Main List View With Builder
          body: ListView.builder(
              itemCount: imgList.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    print("button pressed");
                    print(index);
                  },
                  child: Container(
                    margin: const EdgeInsets.symmetric(
                      vertical: 2.0,
                      horizontal: 8.0,
                    ),
                    child: Stack(
                      children: <Widget>[
                        cardDesign,
                        cardImage,
                      ],
                    ),
                  ),
                ); // gesturedetector
              }));

我哪里做错了?

vfh0ocws

vfh0ocws1#

尝试使用Column而不是Stack

ListView.builder(
          shrinkWrap: true,
          itemCount: 10,
          itemBuilder: (context, index) {
            return GestureDetector(
               onTap: () {
                print("button pressed");
                print(index);
              },
              child: Container(
                margin: const EdgeInsets.symmetric(
                  vertical: 2.0,
                  horizontal: 8.0,
                ),
                child: Column(
                  children: <Widget>[
                    Text(index.toString()),//put your widgets here
                  ],
                ),
              ),
            ); // gesturedetector
          }),
km0tfn4u

km0tfn4u2#

您可以在ListView中使用ListTile,因为ListTile具有onTap功能,此处相同:

ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  return Card(
                    child: ListTile(
                      title: Text('TextHere'),
                      onTap: () {
                        log('on tap');
                      },
                    ),
                  );
                });

相关问题