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

Flutter路由配置调用Widget类型报NoSuchMethodError错误如何解决

错误产生原因

你在bottomBar配置中给page字段赋值的是HomeView/CMView等类本身,对应Dart中Type类型的对象,而不是可以生成对应Widget实例的可调用对象。你在RoutesSwitcher中执行routeConfig['page']()时,相当于尝试调用Type类型对象的call方法,而Type类本身没有定义call方法,因此抛出该NoSuchMethodError异常。

修复方案

最优方案是修改路由配置的page字段,将其改为构造函数引用或者返回Widget实例的函数,修改后无需调整RoutesSwitcher的调用逻辑:

  1. 如果你使用的Dart版本 >=2.15(Flutter 2.8+ 默认支持),可以使用构造函数tear-off写法类名.new:
// config dart
import 'package:flutter/material.dart';
import 'package:offline_solution/pages/pages.dart';

Map<int, Map<String, dynamic>> bottomBar = {
 0: {"path": "Home", "icon": Icons.home, "page": HomeView.new, "initial": true},
 1: {
      "path": "CM",
      "icon": Icons.dashboard,
      "page": CMView.new,
      "initial": false
 },
 2: {
     "path": "PM",
     "icon": Icons.view_agenda,
     "page": PMView.new,
     "initial": false
 },
 3: {
   "path": "Messages",
   "icon": Icons.notifications,
   "page": NotificationView.new,
   "initial": false
  }
};
  1. 如果你需要兼容更低版本的Dart,可以改用箭头函数写法:
    将每个page字段的值改为() => 类名(),示例:
    "page": () => HomeView()

额外优化建议

你可以把配置中page字段的类型从dynamic明确声明为Widget Function(),这样编译期就能提前发现类型不匹配的问题,不用等到运行时才抛出异常。

// 类型更安全的配置写法
Map<int, Map<String, Object>> bottomBar = {
  0: {"path": "Home", "icon": Icons.home, "page": HomeView.new as Widget Function(), "initial": true},
  // 其余项同理
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 17:45:04