【问题标题】:"Avoid using private types in public APIs" Warning in Flutter“避免在公共 API 中使用私有类型” Flutter 中的警告
【发布时间】:2022-11-06 07:56:30
【问题描述】:

我一直在做一个颤振项目,我注意到了避免在公共 API 中使用私有类型. 有没有办法解决这个警告?

 class SubCategoriesPage extends StatefulWidget {
  final MainModel mainModel;

  // final Ads ad;

  const SubCategoriesPage(this.mainModel, {Key? key}) : super(key: key);

  @override
  _SubCategoriesPage createState() { // Avoid using private types in public APIs.
    return _SubCategoriesPage();
  }
}

【问题讨论】:

标签: flutter dart


【解决方案1】:

因为createState 方法返回State<Example>,所以它阻止返回任何私有State

您需要像这样更新您的代码。

class SubCategoriesPage extends StatefulWidget {
  final MainModel mainModel;

  // final Ads ad;

  const SubCategoriesPage(this.mainModel, {Key? key}) : super(key: key);

  @override
  State<SubCategoriesPage> createState() { // Avoid using private types in public APIs.
    return _SubCategoriesPage();
  }
}

【讨论】:

    【解决方案2】:

    因为这是一个StatefulWidget,我猜_SubCategoriesPage 类继承自State,因为它是由createState() 返回的。

    如果是这样,返回类型可以更改为State。由于State 是公开的,因此可以安全地从公开的createState() 方法返回。

    【讨论】:

    • 非常感谢您的回答。但是您能否提供我需要在此代码中进行的更改?
    【解决方案3】:

    使用此代码我遇到了同样的问题

    class MyPage extends StatefulWidget {
      const MyPage({super.key});
    
      @override
      _MyPageState createState() => _MyPageState();
      }
    

    我尝试使用这种方法 - State createState() { // 避免在公共 API 中使用私有类型。 返回 _MyPageState(); 但比我收到此错误消息 - 名称 MyPageState 不是类型,因此它不能用作类型参数。

    【讨论】:

      【解决方案4】:

      只需将_SubCategoriesPage 更改为State

      对于使用 Riverpod 的用户,请将 _SubCategoriesPage 更改为 ConsumerState

      【讨论】:

        猜你喜欢
        • 2022-07-22
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2019-10-04
        • 2020-06-03
        • 1970-01-01
        相关资源
        最近更新 更多