Categories
Flutter Mobile Development

Flutter: Read config data

Many times we need to be able to read configuration information inside our app at runtime. See how to do this in flutter

Intro

If you come from a web background (php/node) you know how to load application config information from .env or .json files. In this article i show you how do the same in flutter.

we do this in order to load information such as api keys that are needed to connect to or consume thirdparty resources.


It is considered bad practise to store api keys inside you application source code, which may endup in a public repository, so embedding API keys inside source code is out of question.


The only viable solution is to read from a config file on application start up and store the required data securily on the device. In this article i will only talk about how to read data from a config file, we will see how to store this data securely on this device in a future article.


To achieve the same level of functionality we rely on the rootBundle object which is available from “package:flutter/services.dart”

Setup

The way to access config data at runtime in flutter is as follows

  • specify the location of the config file inside pubspec.yaml
  • import services.dart from flutter, this package provides functions to read assetbundles at run time.
  • read config data by using DefaultAssetBundle function.

The sample application i have included uses a stateful widget. Inside the initState function of this widget we call the loadConfig function. This is an async function which returns a future.

Once the future is resolved we call setState function. Inside the setState function we use the jsonDecode function from dart:convert package to json decode the response and extract the values, these values are then set to the variables in the class


we first need to specify in pubspec.yaml where our data is coming. Open pubsepc.yaml file and uncomment the assets section. Then add the location to the config file.

In this example i have created a file called test.json, which is located inside the assets older

Next, add the required imports to the code

import 'package:flutter/services.dart' show DefaultAssetBundle;
import 'dart:async' show Future;

we need ‘dart:aync’ to parse the json response returned from loadConfig async function.

This is an excerpt from main.dart.

class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    }

    class _MyAppState extends State<MyApp> {
      String configData;

      Future<String> loadConfig() async {
        return await DefaultAssetBundle.of(context).loadString('assets/test.json');
      }

      @override
      void initState() {
        loadAsset().then((data) {
          Map decodedData = jsonDecode(data);
          setState(() {
            configData = decodedData['api_key'];
          });
        });

        super.initState();
      }

      @override
      Widget build(BuildContext context) {
        print(configData);
        return MaterialApp(
          home: Scaffold(
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "Api key",
                    style: TextStyle(
                      fontSize: 20.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Text("$configData"),
                ],
              ),
            ),
          ),
        );
      }
    }

This is what we end up with

Quick Summary

  • Use DefaultAssetBundle from ‘services.dart’ to read asset bundle data
  • Specify location of config data inside puspec.yaml
  • NEVER check in config file with sensitive data

Code

Download the code here.

If you find this code useful please give it a star so that others may find it too 🙂

Sign up to be notified of new posts. I promise i won’t spam you.

Leave a Reply

Your email address will not be published.