Flutter中SpeedDial跳转notas页面报错:需2个位置参数但未传入
解决Flutter跳转页面时“2 positional argument(s) expected, but 0 found”错误
这个错误的核心原因是notas类的构造函数要求必须传入data和ref两个位置参数,但你跳转时调用notas()没有传参,导致参数缺失。以下是具体解决步骤:
1. 确认参数来源
先明确当前页面中data(Map类型)和ref(DocumentReference类型)的实例来源:比如是从Firebase查询返回的DocumentSnapshot的data()和reference属性,或是当前页面定义好的对应变量。
2. 修改跳转代码,传入参数
假设当前页面已有targetData(Map类型)和targetRef(DocumentReference类型)两个变量,修改SpeedDial的onTap逻辑:
onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => notas(targetData, targetRef), )); }
3. 优化构造函数(可选但推荐)
为避免位置参数的顺序混淆,建议将构造函数改为命名参数+required修饰的写法,提升代码可读性:
class notes extends StatefulWidget { final Map data; final DocumentReference ref; late String tituloTexto; late String notaTexto; late String nomCuaderno; // 命名参数写法 notes({required this.data, required this.ref}); @override State<notes> createState() => _notasState(); }
对应的跳转代码也改为命名参数传递:
onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => notas( data: targetData, ref: targetRef, ), )); }
4. 排查参数传入后的问题
若传入参数后仍报错,检查以下几点:
- 传入的
data必须是Map类型,ref必须是DocumentReference类型,类型不匹配会触发错误 - 确保传入的变量已完成初始化,不为null(构造函数中
data和ref是final属性,必须传入非null值) - 检查变量名拼写,避免笔误导致参数未正确传入
额外提示:Dart命名规范
按照Dart编码惯例,类名应首字母大写,建议将notes改为Notes,_notasState改为_NotesState,让代码更符合社区规范,提升可读性。
内容的提问来源于stack exchange,提问作者FacuPapayannis
相关产品推荐
相关产品推荐

