【问题标题】:How to access config file in flutter using bloc architecture如何使用 bloc 架构访问 Flutter 中的配置文件
【发布时间】:2020-05-26 17:12:45
【问题描述】:

在我的 Flutter 应用程序中,我将构建环境 dev 和 prod 分开。为了实现这一点,我创建了一个扩展继承小部件的 AppConfig 类。

class AppConfig extends InheritedWidget {
  AppConfig({
    @required this.title,
    @required this.clientId,
    @required this.redirectUrl,
    @required this.discoveryUrl,
    @required this.scopes,
    @required this.apiBaseUrl,
    @required Widget child,
  }) : super(child: child);

  final String title;
  final String clientId;
  final String redirectUrl;
  final String discoveryUrl;
  final String apiBaseUrl;
  final List<String> scopes;

  static AppConfig of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<AppConfig>();
  }

  @override
  bool updateShouldNotify(InheritedWidget oldWidget) => false;
}

在视图中它工作正常,我可以像这样访问配置文件:_config = AppConfig.of(context);

我在我的应用程序中遵循 BLoC 架构模式。是否可以访问 bloc 或网络层上的配置文件?例如在我的 API 提供程序中。问题是,我在这些课程中没有上下文。目标应该是这样的。

  Future<dynamic> get(String url) async {
    _config = AppConfig.of(context);
}

我怎样才能做到这一点?

【问题讨论】:

    标签: flutter config bloc


    【解决方案1】:

    我正在寻找相同的解决方案。如果找到请提供。

    更新:检查此链接,这是单例解决方案:

    https://medium.com/flutter-community/flutter-ready-to-go-e59873f9d7de

    【讨论】:

      【解决方案2】:

      AppConfig 可以是全局单例,您不需要为此使用InheritedWidget,而是使用普通的 dart 类。因此,您可以使用服务定位器来设置实例。然后从应用程序的任何位置访问实例,而无需上下文对象。

      要设置服务定位器,您可以使用this 包。文档中提供了详细示例。

      【讨论】:

        猜你喜欢
        • 2021-11-02
        • 2019-08-22
        • 2020-04-11
        • 2021-07-05
        • 2019-06-13
        • 2021-10-26
        • 2020-09-26
        • 2021-06-17
        • 2019-10-11
        相关资源
        最近更新 更多