You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何使用TapGestureRecognizer实现点击富文本跳转页面

修复方案

核心问题原因

  • 你声明的TapGestureRecognizer没有绑定onTap点击回调,所以点击事件没有被触发,自然无法跳转
  • CreateAccount类中return语句后的throw UnimplementedError()属于无效代码,直接删除即可

方法1:继续使用TapGestureRecognizer实现跳转

需要给手势识别器绑定onTap回调,在回调中调用Flutter的路由跳转APINavigator.push,修改后的代码如下:

margin: const EdgeInsets.only(top: 25.0),
child: RichText(
  text: TextSpan(
      children: [
        const TextSpan(
            text: 'I do not have an account',
            style: TextStyle(color: Colors.black87)
        ),
        TextSpan(
            text: ' Create account',
            style: const TextStyle(color: Color.fromRGBO(24, 44, 228, 1)),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                // 路由跳转到注册页
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => const CreateAccount())
                );
              }
        ),
      ]
  ),
),

对应的CreateAccount类修改后:

class CreateAccount extends StatelessWidget{
  const CreateAccount({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Create account'),
      ),
    );
  }
}

方法2:更易维护的替代方案

如果不需要严格在文本流里嵌套可点击文本,更推荐用Row组件包裹普通文本和TextButton实现,代码可读性更高,后续修改样式和交互也更方便:

margin: const EdgeInsets.only(top: 25.0),
child: Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    const Text('I do not have an account', style: TextStyle(color: Colors.black87)),
    TextButton(
      onPressed: () => Navigator.of(context).push(MaterialPageRoute(builder: (context) => const CreateAccount())),
      child: const Text('Create account', style: TextStyle(color: Color.fromRGBO(24, 44, 228, 1))),
    )
  ],
),

内容的提问来源于stack exchange,提问作者Ifeoluwa Wole-Osho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 22:36:04