调用函数引用时不使用命名参数时出错

问题描述 投票:0回答:1

我收到以下错误: 参数类型“void Function(String?)”无法分配给参数类型“void Function()?” 当我在代码中这样做时:

void openNoteBox(String? docID) {}
...
***onPressed: openNoteBox //Error here***
...
onPressed: () => openNoteBox(docID), // it works here
...
This fixed it:
void openNoteBox({String? docID}) {}
...
***onPressed: openNoteBox, //error is gone here***
...
onPressed: () => openNoteBox(docID: docID),
...

但是为什么前一个不起作用?

flutter function dart parentheses named-parameters
1个回答
0
投票

在第一个代码中,您定义了所需的位置参数。要定义可选位置参数,请使用以下语法:

void openNoteBox([String? docID]) {}

在第二个代码中,您定义了一个命名参数,默认情况下该参数是可选的。来自文档

命名参数是可选的,除非它们被明确标记为

required

© www.soinside.com 2019 - 2024. All rights reserved.