A generator to create config class from json files that support many environments

Overview

A generator to create config class from json files that support many environments.

Motivation

If you use a json file to config your applications, perphaps you need to write a dart class that contain all variables you define with their data types. When you need to manage nested objects is more complicated. Even if you want to add or delete a value in your json, you need to modify your dart class.

If you want to manage environments you need to writte manually the file path for every enviroment you need.

json_config_generator wants to help you to have an easy process with the manage of config files and environments.

Install

To use json_config_generator, you will need build_runner/code-generator setup.
First, install build_runner and json_config_generator by adding them to your pubspec.yaml file:

pubspec.yaml

dependencies:
  json_config_annotation: ^0.1.0

dev_dependencies:
  build_runner:
  json_config_generator: ^0.1.0

How to use

To use this generator need to create an empty config dart class that begins with $ using the annotation Configuration defining the environments that you want to have. Each environment has name and path, if have more that one, the generator create an Enum to environments. Also you can specify the name of that Enum. By default it's name is Environment. Also, you need to add some imports.

config.dart

import 'package:json_config_annotation/json_config_annotation.dart';
import 'dart:convert';
import 'package:flutter/services.dart';

part 'config.g.dart'; //{dart file name}.g.dart

@Configuration(
  environmentEnumName: 'Env',
  environments:[
    Environment(name:'dev', path:'assets/config/dev.json'),
    Environment(name:'prd', path:'assets/config/prd.json'),
  ],
)
class $Config{}

suposing that have the next json file

dev.json

{
  "base_url": "https://example.com",
  "custom_class": {
    "value_1": "dfgdfgdfgwqrrqwrqwrqweqwe324523b252dghfdhd",
    "value_2": "6Lez7aIaAAAAAN6qZG2343c252bv66b7yn5m8m6"
  },
  "int_value": 3,
  "double_value": 3.5,
  "boolean_value": true,
  "string_list": ["hello", "world"],
  "int_list": [1, 23, 5],
  "bool_list": [false, true, true],
  "custom_list": [
    {
      "value_1": "hello"
    },
    {
      "value_1": "world"
    }
  ]
}

the generator creates

config.g.dart

enum Env { dev, prd }

class Config {
  Config._();

  static final instance = Config._();

  late String baseUrl;

  late _CustomClass customClass;

  late int intValue;

  late double doubleValue;

  late bool booleanValue;

  late List<String> stringList;

  late List<int> intList;

  late List<bool> boolList;

  late List<_CustomList> customList;

  Future<void> init(Env env) async {
    String path = '';
    switch (env) {
      case Env.dev:
        path = 'assets/config/dev.json';
        break;
      case Env.prd:
        path = 'assets/config/prd.json';
        break;
    }
    final jsonString = await rootBundle.loadString(path);
    final config = json.decode(jsonString) as Map<String, dynamic>;
    baseUrl = config['base_url'] as String;
    customClass =
        _CustomClass.fromJson(config['custom_class'] as Map<String, dynamic>);
    intValue = config['int_value'] as int;
    doubleValue = config['double_value'] as double;
    booleanValue = config['boolean_value'] as bool;
    stringList = (config['string_list'] as List).cast<String>();
    intList = (config['int_list'] as List).cast<int>();
    boolList = (config['bool_list'] as List).cast<bool>();
    customList = _CustomList.listFromJson(config['custom_list'] as List);
  }
}

class _CustomClass {
  const _CustomClass({required this.value1, required this.value2});

  factory _CustomClass.fromJson(Map<String, dynamic> customClass) =>
      _CustomClass(
        value1: customClass['value_1'] as String,
        value2: customClass['value_2'] as String,
      );

  final String value1;

  final String value2;
}

class _CustomList {
  const _CustomList({required this.value1});

  factory _CustomList.fromJson(Map<String, dynamic> customList) => _CustomList(
        value1: customList['value_1'] as String,
      );

  final String value1;

  static List<_CustomList> listFromJson(List data) =>
      data.map((e) => _CustomList.fromJson(e as Map<String, dynamic>)).toList();
}

To use the generated configuration you need to call init method to initialize all values. Could be called in main defining the Environment that you want to use.

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Config.instance.init(Env.dev);
  runApp(const MyApp());
}

Now can access to fields easy using the instance

Config.instance.baseUrl;
Config.instance.customClass.value1;

Supported data types

- String
- int
- double
- bool
- CustomClass
- List<String>
- List<int>
- List<double>
- List<bool>
- List<CustomClass>

Also can create nested classes!

Important

  • Do not support nullable values
  • Do not support dynamic values

Run the generator

To run the generator use one of the next commands:

  • flutter pub run build_runner build
  • dart pub run build_runner build

Considerations

Can also create a config with only one Environment. If that so, the Enum do not be created and when call init method, do not need to pass any argument.

It is important to known that the generator takes the first value in lists to known the type of the list, so be caferull

You might also like...

AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code.

async_call_queue AsyncCallQueue is a Dart class which provides a queuing mechanism to prevent concurrent access to asynchronous code. Getting Started

Jan 18, 2022

Automatically generate usecase classes from your repository class definition in Dart and Flutter

Automatically generate usecase classes from your repository class definition in Dart and Flutter

Repo Case Automatically generate usecase classes from your repository class definition in Dart and Flutter. Check out the official guide on repo_case

Jul 30, 2022

A builder that generates an ArgsParser from a class

Parse command line arguments directly into an annotation class using the Dart Build System. Example Annotate a class with @CliOptions() from package:b

Oct 30, 2022

This is a simple class to package up and send requests to the Kroki.io web service.

Kroki.dart This is a simple class to package up and send requests to the Kroki.io web service. A live editor to editing diagrams that Kroki supports c

Jun 8, 2022

Starter project and code generator for Flutter/Redux

Starter project and code generator for Flutter/Redux

Flutter Redux Starter/Code Generator Videos Short video ~ 1 minute Long video ~ 10 minutes We're using this approach to develop the Flutter app for In

Dec 12, 2022

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs.

The Flutter code generator for your assets, fonts, colors, … — Get rid of all String-based APIs. Inspired by SwiftGen. Motivation Using asset path str

Jan 6, 2023

🚀The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time.

🚀The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time.

Flutter Gen Zeplin Extension 🚀 The Flutter dart code generator from zeplin. ex) Container, Text, Color, TextStyle, ... - Save your time. ⬇ 1.1k Getti

Oct 12, 2022

GPT-3 recipe generator for the GPT-3 Makeathon by TUM.AI. Developed by team Taste the data.

GPT-3 recipe generator for the GPT-3 Makeathon by TUM.AI. Developed by team Taste the data.

GPT-3 Makeathon by TUM.AI - Team: Taste the Data Team - Taste the Data: Carmen Heger @stedomedo David Stiftl @stiftlD Christopher Schütz @cdschtz

Dec 4, 2022

Dart Code Generator for generating mapper classes

Smartstruct - Dart bean mappings - the easy nullsafe way! Code generator for generating type-safe mappers in dart, inspired by https://mapstruct.org/

Nov 29, 2022
Owner
Diego Cardenas
Diego Cardenas
library to help you create database on local memory, support json local database inspired by lowdb

Licensed Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2021 Azkadev <http://github.c

Azka Full Snack Developer:) 35 Oct 17, 2022
Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object

Lazy JSON Provides null-safety implementation to simplify JSON data handling by adding extension method to JSON object and JSON array. Getting started

Kinnara Digital Studio 0 Oct 27, 2021
Provide route generator to create route map quickly by annotations.

ff_annotation_route Languages: English | 中文简体 Description Provide a route generator to create route map quickly by annotations. ff_annotation_route De

FlutterCandies 113 Nov 25, 2022
A flutter application , that create dynamic forms from json data

checktyper A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

DotCoder 1 Aug 23, 2022
Let's Encrypt support for the shelf package (free and automatic HTTPS certificate support).

shelf_letsencrypt shelf_letsencrypt brings support for Let's Encrypt to the shelf package. Usage To use the LetsEncrypt class import 'dart:io'; impor

Graciliano Monteiro Passos 8 Oct 31, 2022
Library for help you make userbot or bot telegram and support tdlib telegram database and only support nodejs dart and google-apps-script

To-Do telegram client dart ✅️ support multi token ( bot / userbot ) ✅️ support bot and userbot ✅️ support telegram-bot-api local server ✅️ support tel

Azka Full Snack Developer:) 73 Jan 7, 2023
This is app includes many app.

drawer A new Flutter application. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if th

rudani jemin 6 Oct 1, 2021
Quiver is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient, or adds additional functionality.

Quiver is a set of utility libraries for Dart that makes using many Dart libraries easier and more convenient, or adds additional functionality.

Google 905 Jan 2, 2023
Converts SVG icons to OTF font and generates Flutter-compatible class. Provides an API and a CLI tool.

Fontify The Fontify package provides an easy way to convert SVG icons to OpenType font and generate Flutter-compatible class that contains identifiers

Igor Kharakhordin 88 Oct 28, 2022
A simple Flutter / Dart Utility class for converting complex objects to uri and query string

A simple Flutter / Dart Utility class for converting complex or nested objects to uri and query strings you can follow the the article on how this cla

Opata Joshua 5 Sep 7, 2022