Search code examples
flutterdartmobile

What is the standard way of writing configuration in flutter?


I am new to flutter and no clear documents for creating a config file.What is the standard way of writing configuration in flutter similar to one below which we write in appsettings.json(.net core)?

   "Travel": {
     "EndPoint": "https://api.openai.com/v1/threads",
     "ApiKey": "sk-123",
     "AssistantId": "asst_123"
   },
   "Home": {
     "EndPoint": "https://api.openai.com/v1/threads",
     "ApiKey": "sk-1234",
     "AssistantId": "asst_1234"
   },
   "Edu": {
     "EndPoint": "https://api.openai.com/v1/threads",
     "ApiKey": "sk-123456",
     "AssistantId": "asst_12345"
     }
 }```

Solution

  • You can create a Dart class to represent the structure and store the configuration data. Here's how you can do it:

    class AppConfig {
      static const Map<String, Map<String, String>> config = {
        "Travel": {
          "EndPoint": "https://api.openai.com/v1/threads",
          "ApiKey": "sk-123",
          "AssistantId": "asst_123"
        },
        "Home": {
          "EndPoint": "https://api.openai.com/v1/threads",
          "ApiKey": "sk-1234",
          "AssistantId": "asst_1234"
        },
        "Edu": {
          "EndPoint": "https://api.openai.com/v1/threads",
          "ApiKey": "sk-123456",
          "AssistantId": "asst_12345"
        }
      };
    }
    
    

    In this Dart class:

    AppConfig represents the configuration class.

    config is a static constant map containing the configuration data.

    The keys of the outer map represent different categories (Travel, Home, Edu).

    Each category contains a nested map with configuration details (EndPoint, ApiKey, AssistantId). You can then access this configuration throughout your app like so:

    String travelEndPoint = AppConfig.config["Travel"]["EndPoint"];
    String travelApiKey = AppConfig.config["Travel"]["ApiKey"];
    String travelAssistantId = AppConfig.config["Travel"]["AssistantId"];