Build Extensions for Flutter

Fred Grott
2 min readJul 7, 2019

Okay folks, lets get real professional and have some build extensions so that we can do things like keep web api keys and crash report api keys out of the damn code repo already!

Since mid 2018 Flutter in the beta and dev channels has had a target functionality to the build app commands. Until recently, it was not part of the production release version of the sdk and now it is. But, most had it worng in how to use.

Your first step is modify your gitignore. You want to ignore the dart files of:

main_dev, main_prod, main_stagging. The files we will add are build_env and main_ci dart files.

I am going to give an example of the build_env dart file first. It only sets-up the env variables but does not assign them!

build_env dart file:

import ‘package:meta/meta.dart’;

enum BuildFlavor { prod, dev, staging, ci }

BuildEnvironment get env => _env;

BuildEnvironment _env;

class BuildEnvironment {

final BuildFlavor flavor;

BuildEnvironment._init({this.flavor});

static void init({@required flavor}) =>

_env ??= BuildEnvironment._init(flavor: flavor);

}

For each web api key or other key add the vars in the right places the init and above. Now let me show what the typical gitignore product flavor dart file looks like with main_dev:

import ‘package:flutter/material.dart’;

import ‘package:flutter_app/build_env.dart’;

import ‘package:flutter_app/main.dart’;

void main() {

BuildEnvironment.init(

flavor: BuildFlavor.dev);

assert(env != null);

mainDelegate();

}

Now for the only changes you need to make in the main dart file:

import ‘package:flutter/material.dart’;

import ‘package:flutter_app/build_env.dart;

void mainDelegate() => runApp(MyApp());

The rest of the main dart file is the same and of course you are accessing the env variable to read. Simple, huh?

My small portfolio site is at:

--

--