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

Flutter如何向类传递变量?路径参数传递报错求助

问题解决:"the named parameter 'path' isn't defined"

报错的核心原因是你没有给ItemDetails类定义接收path参数的构造函数,所以调用ItemDetails(path: state.path)时,Dart找不到对应的命名参数。

具体修改步骤:

1. 给ItemDetails添加参数化构造函数

在ItemDetails类中声明一个final类型的path变量,并定义构造函数接收这个参数:

class ItemDetails extends StatelessWidget {
  // 声明final变量存储路径
  final String path;

  // 定义构造函数,接收path参数
  const ItemDetails({super.key, required this.path});

  @override
  Widget build(BuildContext context) {
    // 直接使用传入的path变量
    final Query docRef = FirebaseFirestore.instance
        .collection("Collection_Name")
        .where("path", isEqualTo: path);
    
    return FutureBuilder<QuerySnapshot>(
      future: docRef.get(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            appBar: AppBar(
              title: Text(path),
            ),
            body: const Center(child: CircularProgressIndicator()),
          );
        } else if (snapshot.hasError) {
          return Scaffold(
            appBar: AppBar(
              title: Text(path),
            ),
            body: Center(child: Text("Error: ${snapshot.error}")),
          );
        } else {
          var querySnapshot = snapshot.data!;
          var docs = querySnapshot.docs;
          final data = docs[0].data() as Map<String, dynamic>;

          final yourScrollController = ScrollController();
          return Scaffold(
              appBar: AppBar(
                title: Text(path),
              ),
              // 剩余代码保持不变
          );
        }
      },
    );
  }
}

2. 移除冗余的routeData代码

你原来代码里通过ModalRoute.of(context)?.settings.arguments获取参数的逻辑可以直接删除——用GoRouter时,通过构造函数传参更直接,且原来的强转as Map容易引发类型错误。

3. 验证GoRouter的传参调用

你的GoRouter路由代码无需修改:

builder: (_, state) => ItemDetails(path: state.path),

只要ItemDetails类定义了对应的参数,就能正常传递路径值。

关键说明:

  • StatelessWidget的成员变量必须是final类型,确保不可变,符合StatelessWidget的设计规范。
  • 构造函数中添加super.key是遵循Widget的key传递规范,可选但推荐加上。
  • 所有需要使用路径的地方(AppBar标题、Firestore查询条件)都直接引用类的path成员变量即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:13:17