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

lil*_*uit 7 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"),
);
}
Run Code Online (Sandbox Code Playgroud)

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

代码:

return new SharingDialog(postId);
Run Code Online (Sandbox Code Playgroud)

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

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

die*_*per 9

第一的:

删除 postId 上方的 override 关键字

  @override <-- this one
  final String postId;
Run Code Online (Sandbox Code Playgroud)

第二:

因为您使用的是命名参数,所以像这样发送参数:

   return new SharingDialog(postId: postId);
Run Code Online (Sandbox Code Playgroud)

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

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