Reading configuration files and settings in Flutter and Dart

Suragch
6 min readJul 21, 2021

Comparing plain old Dart, JSON, YAML, and environment variables

Photo by Adi Goldstein

By now you’re used to setting configuration options in pubspec.yaml, but what if you want to define your own config values and read them inside your app? How do you do that? I’ll give you an overview of some options in this article.

Plain old Dart

One easy solution is to just use a plain old Dart class. Create a file named my_config.dart and add the following code:

class MyConfig {
static const String country = 'Mongolia';
static const String animal = 'horse';
}

Then you can use it anywhere in your code by importing that file:

import 'my_config.dart';void main() {
print(MyConfig.country);
print(MyConfig.animal);
}

Using a library rather than a class

There is really no need to use a class name like MyConfig when all it contains is static members. Replace my_config.dart with the following simplified code:

const String country = 'Mongolia';
const String animal = 'horse';

You can still use these values anywhere in your app, but now you can also give them any namespace and show or hide them as you like:

import 'my_config.dart' as config show country;void main() {
print(config.country);
}

The namespace is config and you’re only showing the country variable, so animal won’t be available. This is useful for avoiding naming collisions when you have other variables or libraries in your project.

Don’t tell your secrets

Before going on to the other options, I want to remind you to be careful with any private data you might have in your configuration file. You don’t want to accidentally share that with the entire world by pushing the file to your Git repository. To prevent that you should add the config file to .gitignore.

Open .gitignore and add the name of your configuration file on a new line:

# Configuration
my_config.dart

--

--