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"
}
}```
2
Answers
You can create a Dart class to represent the structure and store the configuration data. Here’s how you can do it:
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:
Several methods commonly used in
Flutter
:JSON
in your project.First add your JSON config file in your project, somewhere like:
config/server.json
. Then update theassets
inpubspec.yaml
:Now, you can load your
JSON
:Dart
file that contains config settings as constants or aclass
withstatic
properties. (My preferred way):And the config repository is like:
This way you can access your data for instance travel data by using
ConfigRepository.travel
.This way you can add some method like finding the data by name (or anyth other properties that you want). (as I mentioned in the class.)
environment variable in flutter
like looking at the packages likeflutter_dotenv
,envied
, etc.