【问题标题】:The argument type 'Widget' can't be assigned to the parameter type 'PreferredSizeWidget?' in null safety参数类型“Widget”不能分配给参数类型“PreferredSizeWidget?”零安全
【发布时间】:2021-05-28 08:30:52
【问题描述】:
Scaffold(
  appBar: _buildAppBar(),
)

函数如下:

Widget _buildAppBar() => AppBar(); // Error

在我将代码迁移到 null 安全性之前,这段代码运行良好。

【问题讨论】:

    标签: flutter dart-null-safety


    【解决方案1】:

    Dart 空安全不允许向下转换,因此您不能将 Widget 分配给 PreferredSizeWidget,就像您不能将 Object 分配给 String 一样(这在空安全之前是可能的) .

    您应该更改您的函数并从中返回 AppBarPreferredSizeWidget

    AppBar _buildAppBar() => AppBar();
    

    PreferredSizeWidget _buildAppBar() => AppBar();
    

    【讨论】:

      【解决方案2】:

      我无法发表评论,但 iDecode 的答案是正确的

      AppBar customAppBar(String title, bool centerTitle, List<Widget> actions) {}
      

      这个错误是空的。

      【讨论】:

        【解决方案3】:
        Scaffold(
          appBar: _buildAppBar() as PreferredSizeWidget?,
        )
        

        【讨论】:

          猜你喜欢
          • 2021-08-23
          • 2021-11-11
          • 2021-12-13
          • 2019-12-06
          • 2020-01-10
          • 2021-08-05
          • 2021-10-04
          • 2021-09-13
          • 2021-08-22
          相关资源
          最近更新 更多