如何在Flutter中将参数传递给小部件

时间:2018-12-06 20:57:44

标签: dart flutter

我正在Flutter中打开一个模态对话框,希望将单个参数(postId)传递给模态以进行进一步处理。但这会产生一个错误,如图所示。

class SharingDialog extends StatefulWidget {
 @override

 final String postId;  // <--- generates the error, "Field doesn't override an inherited getter or setter"
 SharingDialog({
   String postId
 }): this.postId = postId;

 SharingDialogState createState() => new SharingDialogState(postId);
}

class SharingDialogState extends State<SharingDialog> {

 SharingDialogState(this.postId);
 final String postId;

 @override
 Widget build(BuildContext context) {
   return new Scaffold(
     appBar: 
       child: AppBar(           
         title: const Text('Share this Post'),
      actions: [
        new FlatButton(
          onPressed: () {
            print("Sharing Post ID: " + this.postId);
          },
          child: new Text('SHARE)
        ),
      ],
    ),
  ),
  body: new Text("SHARING SCREEN"),
);
}

然后使用以下代码单击以打开模态,该代码会产生伴随的错误:

代码:

return new SharingDialog(postId);

错误:Too many positional arguments: 0 allowed, but 1 found.

如果不是这样,如何传递参数?

1 个答案:

答案 0 :(得分:3)

第一:

在postId上方删除替代关键字

  @override <-- this one
  final String postId;

第二:

因为您使用的是命名参数,所以以这种方式发送参数:

   return new SharingDialog(postId: postId);

如果您想了解有关可选命名参数的更多信息,请查看以下链接:

https://www.dartlang.org/guides/language/language-tour#optional-parameters