How to access config file in flutter using bloc architecture

5,219

Solution 1

I'am looking for same solution. Please provide if you find one.

Update: Check this link, it is solution with singleton:

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

Solution 2

AppConfig can be a global singleton and you don't need to use InheritedWidget for this, instead use a plain dart class. So you can use a service locator to set up the instance. Then access the instance from anywhere on your app without the need for context object.

To set up the service locator, you can use this package. Detailed examples are available on the documentation.

Share:
5,219
Pilouni
Author by

Pilouni

Updated on December 17, 2022

Comments

  • Pilouni
    Pilouni over 1 year

    In my Flutter app, I separate the build environments dev and prod. To achieve this I created an AppConfig class extending an inherited widget.

    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;
    }
    

    In the views it works fine and I can access the config file like this: _config = AppConfig.of(context);

    I am following the BLoC architecture pattern in my app. Is it possible to access the config file on the bloc or networking layer? e.g. in my API provider. The problem is, that I have no context in these classes. The goal would be something like this.

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

    how can I achieve this?