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

Flutter报错:参数类型‘Object?’无法分配给‘Celebrity’类型

解决Flutter路由传参的类型错误问题

问题核心是settings.arguments的类型为Object?,无法直接赋值给要求非空Celebrity类型的CelebrityScreen参数,触发类型不匹配错误。

解决步骤

  • 先对settings.arguments做类型校验,确认它是Celebrity实例
  • 校验通过后,将其强制转换为Celebrity类型再传递给页面;不匹配时返回错误页面,避免运行时崩溃

修改后的RouteGenerator代码

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/':
        return MaterialPageRoute(builder: (context) => CelebrityList());
      case '/celebrity':
        // 检查参数是否为Celebrity类型
        if (settings.arguments is Celebrity) {
          final Celebrity celebrity = settings.arguments as Celebrity;
          return PageRouteBuilder(
            pageBuilder: (context, animation, secondaryAnimation) => CelebrityScreen(celebrity: celebrity),
          );
        } else {
          // 参数类型错误时返回错误页面
          return MaterialPageRoute(
            builder: (context) => Scaffold(
              appBar: AppBar(title: const Text("参数错误")),
              body: const Center(child: Text("传递的参数类型不正确")),
            ),
          );
        }
      default:
        return MaterialPageRoute(
            builder: (context) => Scaffold(
                  appBar: AppBar(
                    title: const Text("Error"),
                  ),
                  body: const Center(
                    child: Text("Page not found"),
                  ),
                ));
    }
  }
}

额外说明

如果你的场景中可以确保传递的参数一定是Celebrity类型,也可以用空断言(!)结合类型转换,但这种方式风险较高,一旦参数类型不匹配会直接崩溃:

// 仅在确定参数非空且类型正确时使用
final Celebrity celebrity = settings.arguments as Celebrity;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:28:01