如何在Stateful Widget之间传递数据?Firebase快照数据向BottomSheet组件传递报错解决
解决Flutter中BottomSheet传递数据的参数报错问题
嘿,我一眼就瞅到问题所在啦!你碰到的Too many positional arguments: 0 expected, but 1 found.报错,根源是构造函数的传参方式不匹配。
问题原因
你定义BottomSheetWidget的构造函数时用了命名参数(包裹在大括号{}里的this.author),但调用它的时候却用了位置参数的写法:
return BottomSheetWidget(author); // 这里是位置参数传参,但构造函数定义的是命名参数
Dart对这两种传参方式区分得很严格,所以编译器会报错说“预期0个位置参数,但你传了1个”。
两种修复方案
你可以任选一种适合你的方式来修复:
方案1:用命名参数调用(推荐保持命名参数的写法)
只需要在调用BottomSheetWidget时加上参数名即可:
void displayBottomSheet(BuildContext context, String author) { showModalBottomSheet( context: context, builder: (ctx) { // 这里改成命名参数传参 return BottomSheetWidget(author: author); }); }
如果你的Dart版本是2.12+(空安全版本),建议给构造函数的参数加上required关键字,明确标记它是必填参数:
class BottomSheetWidget extends Stateful Widget { final String author; // 加上required确保参数必填 BottomSheetWidget({required this.author}); @override class _BottomSheetWidgetState createState() => _BottomSheetWidgetState(); }
方案2:改成位置参数传递
如果你更习惯用位置参数的写法,可以修改BottomSheetWidget的构造函数,去掉包裹参数的大括号:
class BottomSheetWidget extends Stateful Widget { final String author; // 去掉大括号,变成位置必填参数 BottomSheetWidget(this.author); @override class _BottomSheetWidgetState createState() => _BottomSheetWidgetState(); }
这样你原来的调用方式BottomSheetWidget(author)就可以正常运行了。
修复后的完整代码示例(以方案1为例)
主Widget中的代码:
Widget build(BuildContext context) { return Container( child: ElevatedButton( child: Text('Request a tour'), onPressed: () { displayBottomSheet(context, widget.snapshot.data()["author"]); }, ), ); } void displayBottomSheet(BuildContext context, String author) { showModalBottomSheet( context: context, builder: (ctx) { return BottomSheetWidget(author: author); }); }
BottomSheetWidget的代码:
class BottomSheetWidget extends Stateful Widget { final String author; BottomSheetWidget({required this.author}); @override class _BottomSheetWidgetState createState() => _BottomSheetWidgetState(); } class _BottomSheetWidgetState extends State<BottomSheetWidget> { Widget build(BuildContext context) { return Container( child: ElevatedButton( child: Text('Send'), onPressed: () { requestTour(widget.author); }, ), // ...其他组件代码 ); } requestTour(String userName) async { // ...你的业务逻辑 } }
这样修改后,数据就能正常传递到BottomSheet里,报错也会消失啦!
内容的提问来源于stack exchange,提问作者icantcode
相关产品推荐
相关产品推荐

