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

12
我正在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);

错误:位置参数太多:不允许0个,但找到1个。
如果不是这种方式,您如何传递参数?
1个回答

14

首先:

将postId上方的override关键字删除

  @override <-- this one
  final String postId;

第二点:

由于您正在使用命名参数,因此请以以下方式发送参数:

   return new SharingDialog(postId: postId);

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接