Flutter 中可以使用 BuildContext 来添加点击事件,具体步骤如下:

  1. 在需要添加点击事件的 widget 中使用 GestureDetector 包裹起来。

  2. 在 GestureDetector 中添加 onTap 回调函数,该函数接收一个参数 TapDownDetails,可以获取到点击的位置信息。

  3. 在回调函数中可以使用 Navigator.push 方法来实现页面跳转等操作。

示例代码如下:

GestureDetector(
  onTap: () {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => NextPage()),
    );
  },
  child: Container(
    width: 100,
    height: 100,
    color: Colors.blue,
    child: Center(
      child: Text(
        'Click Me',
        style: TextStyle(color: Colors.white),
      ),
    ),
  ),
);

在上述代码中,我们使用 GestureDetector 包裹了一个 Container,当用户点击 Container 时,会触发 onTap 回调函数,该函数中使用 Navigator.push 方法来实现页面跳转。

Flutter Context 点击事件添加教程:使用 GestureDetector 实现页面跳转

原文地址: https://www.cveoy.top/t/topic/kvOH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录