为什么DropdownButton必须在名为getDropdownBotton的函数之前?

时间:2019-12-17 15:17:55

标签: function flutter return

我正在Flutter中编写一些代码,但我不明白为什么我必须用这种方式编写它。 如果我想返回DropdownButton,为什么名称必须在函数getDropdownBotton之前?我的意思是,为什么我必须编写它?为什么没有它,该代码也无法工作?另外,为什么我在返回DropdownButton时必须写?

DropdownButton<String> getDropdownBotton() {
  return DropdownButton<String>(
    value: selectedCurrency,
    items: getDropdownItems(),
    onChanged: (value) {
      setState(() {
        selectedCurrency = value;
      });
    },
  );
}

1 个答案:

答案 0 :(得分:0)

之所以为诸如DropdownButton之类的内容编写<String>是因为Dart(Flutter使用的语言)不喜欢推断类型。当然可以,但是建议您自己声明。

关于为什么必须声明返回类型(方法名称之前的内容)的原因,Dart也不喜欢推断类型。您可以删除类型DropdownButton<String>,Dart会推断出返回类型。

getDropdownBotton() { // Dart will now infer the type and secretly, the keyword `dynamic` is there to let it know it could return anything
  return DropdownButton<String>(
    value: selectedCurrency,
    items: getDropdownItems(),
    onChanged: (value) {
      setState(() {
        selectedCurrency = value;
      });
    },
  );
}

return是必需的,因为您希望函数给您一些东西,在这种情况下为DropdownButton。如果没有关键字return,Dart将只执行代码并将其全部保留(我知道,贪婪吧?)。使用return关键字,现在调用此方法的小部件将能够从getDropdownBotton获取一个下拉按钮来使用。

PS :您的函数拼写错误,应为getDropdownButton