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

Flutter类导航组件返回Null问题求助

问题解决:navigationToRoute参数始终为Null的原因及修复

问题根源

你遇到的核心问题是未将构造函数传入的navigationToRoute参数保存为类的成员变量。在socialTile类的构造函数中,你仅声明了该参数,但没有将其赋值给类的属性,导致build方法的onTap回调里访问的navigationToRoute并非你传入的函数,因此始终返回null。

修复步骤

  1. 在socialTile类中添加navigationToRoute的成员变量声明(用final修饰)
  2. 在构造函数中,将参数赋值给这个成员变量

修改后的完整socialTile类代码

class socialTile extends GeneralUITile {
  const socialTile({
    Key? key,
    this.tileTitle = '',
    this.inputIcon,
    Widget Function(BuildContext)? navigationToRoute,
  }) : this.navigationToRoute = navigationToRoute,
       super(key: key);

  final String tileTitle;
  final Icon? inputIcon;
  final Widget Function(BuildContext)? navigationToRoute; // 新增成员变量

  @override
  Widget build(BuildContext context) {
    return Container(
      child: GestureDetector(
        onTap: () {
          print('$navigationToRoute Tap registered');
          if (navigationToRoute != null) {
            Navigator.push(
              context,
              MaterialPageRoute(builder: navigationToRoute!),
            );
          }
        },
        child: Container(
          height: 175,
          width: 175,
          color: Colors.purpleAccent,
          alignment: Alignment.center,
          child: Column(
            children: [
              if (inputIcon != null) ...[inputIcon!],
              Text(
                '$tileTitle',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

补充说明

  • 若希望navigationToRoute为可选参数,保持原参数的?标记即可,无需添加required;如果要求必须传入,则可以加上required修饰参数。
  • 按照Dart命名规范,类名建议采用大驼峰命名法,可将socialTile改为SocialTile,提升代码可读性。

内容的提问来源于stack exchange,提问作者Rhumph

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 00:32:54